python 分割txt

def split_file(file_path, num_parts):
# 读取原始文件的所有行
with open(file_path, 'r', encoding='utf-8') as f:
lines = f.readlines()

# 计算每个部分应包含的行数
num_lines_per_part = len(lines) // num_parts

# 分割文件
for i in range(num_parts):
start_idx = i * num_lines_per_part
end_idx = start_idx + num_lines_per_part if i < num_parts - 1 else None

# 构造新文件名
new_file_path = f"{file_path[:-10]}_part_{i + 1}.txt"

# 写入部分内容到新文件
with open(new_file_path, 'w', encoding='utf-8') as new_file:
new_file.writelines(lines[start_idx:end_idx])

if __name__ == "__main__":
file_path = 'domain.txt'
num_parts = 4#分割成四份
split_file(file_path, num_parts)

 

posted @ 2024-08-08 16:40  射满东城湖  阅读(87)  评论(0)    收藏  举报