在Python中,循环读取数据通常有以下几种方法:
1. 使用`for`循环逐行读取文件:
with open('filename.txt', 'r') as file:
for line in file:
处理每一行的操作
print(line.strip()) 使用strip()去除行尾的换行符
2. 使用`while`循环和`readline()`方法逐行读取文件:
with open('filename.txt', 'r') as file:
line = file.readline()
while line:
处理每一行的操作
print(line.strip()) 使用strip()去除行尾的换行符
line = file.readline()
3. 使用`readlines()`方法一次性读取文件的所有行,然后进行循环处理:
with open('filename.txt', 'r') as file:
lines = file.readlines()
for line in lines:
处理每一行的操作
print(line.strip()) 使用strip()去除行尾的换行符
4. 使用`glob`模块获取文件列表,然后循环读取每个文件的内容:
import glob
file_list = glob.glob('*.txt') 获取当前目录下所有.txt文件
for file in file_list:
with open(file, 'r') as f:
for line in f:
处理每一行的操作
print(line.strip()) 使用strip()去除行尾的换行符
5. 读取Excel文件中的数据:
import openpyxl
workbook = openpyxl.load_workbook('path_to_excel_file.xlsx')
worksheet = workbook['Sheet1']
start_row = 2
end_row = 22
column_number = 2
output_file_path = 'output.txt'
with open(output_file_path, 'w') as output_file:
for row_number in range(start_row, end_row + 1):
cell_value = worksheet.cell(row=row_number, column=column_number).value
if cell_value is not None:
output_file.write(str(cell_value) + '\n') 将单元格值写入文件,并换行
6. 使用`pandas`读取和处理CSV文件:
import os
import pandas as pd
df_list = []
for file in os.listdir():
if file.endswith('.csv'):
df_list.append(pd.read_csv(file))
对df_list中的每个DataFrame进行处理,例如合并到一个大的DataFrame中
df = pd.concat(df_list)
使用`with`语句可以确保文件在使用完毕后被正确关闭,即使在处理文件过程中发生异常也是如此。