在Python中读取数据通常有以下几种方法:
1. 使用内置的`open()`函数读取文本文件:
with open('file_name.txt', 'r', encoding='utf-8') as file:content = file.read()print(content)
2. 使用`readline()`方法逐行读取文件内容:
with open('file_name.txt', 'r', encoding='utf-8') as file:line = file.readline()while line:print(line.strip())line = file.readline()
3. 使用`readlines()`方法一次性读取整个文件内容,并返回一个列表:
with open('file_name.txt', 'r', encoding='utf-8') as file:lines = file.readlines()for line in lines:print(line.strip())
4. 使用`csv`模块读取CSV文件:
import csvwith open('file_name.csv', 'r', encoding='utf-8') as csvfile:reader = csv.reader(csvfile)for row in reader:print(row)

5. 使用`pandas`库读取数据:
import pandas as pddf = pd.read_csv('file_name.csv')print(df.head())
6. 使用`datatable`库读取大量数据:
import datatable as dttrain_datatable = dt.fread('file_name.csv')train = train_datatable.to_pandas()print(train.head())
7. 使用`openpyxl`或`xlrd`库读取Excel文件:
使用 openpyxlfrom openpyxl import load_workbookwb = load_workbook('file_name.xlsx')sheet = wb.activefor row in sheet.iter_rows():for cell in row:print(cell.value)使用 xlrdimport xlrdworkbook = xlrd.open_workbook('file_name.xls')sheet = workbook.sheet_by_index(0)for row_index in range(sheet.nrows):row_data = sheet.row_values(row_index)print(row_data)
