在Python中,如果你想要按行分割一个文件,你可以使用以下方法:
1. 使用`readlines()`方法读取文件,并逐行处理。
with open('file.txt', 'r') as file:
lines = file.readlines()
for line in lines:
处理每一行
print(line.strip()) 去除行尾的换行符
2. 使用`splitlines()`方法直接按行分割文件内容。
with open('file.txt', 'r') as file:
lines = file.read().splitlines()
for line in lines:
处理每一行
print(line)
3. 使用`for`循环逐行读取文件。
with open('file.txt', 'r') as file:
for line in file:
处理每一行
print(line.strip())
4. 使用`pandas`库分割Excel文件。
import pandas as pd
def split_excel(file, num_sheets):
file_dir = 'result'
if os.path.isdir(file_dir):
os.rmdir(file_dir)
else:
os.mkdir(file_dir)
df = pd.read_excel(file)
row_num = len(df)
if num_sheets >= row_num:
raise Exception('Too many sheets!')
for i in range(num_sheets, row_num, num_sheets):
df_part = df.iloc[i-num_sheets:i]
output_file = os.path.join(file_dir, f'sheet_{i//num_sheets + 1}.xlsx')
df_part.to_excel(output_file, index=False)
5. 使用`os`和`subprocess`模块执行shell命令来分割文本文件。
import os
import subprocess
def split_file_by_row(filepath, new_filepath, row_cnt, suffix_type='txt'):
temp_count = 0
part_num = 1
with open(filepath, 'r') as f:
with open(new_filepath, 'w') as new_f:
for line in f:
if temp_count < row_cnt:
temp_count += 1
new_f.write(line)
else:
part_num += 1
temp_count = 1
new_f.write(line)
以上方法可以帮助你按行分割文件。如果你需要分割的是CSV文件,可以使用`csv.reader`来逐行读取和处理数据。
请根据你的具体需求选择合适的方法。