如何在 Python 3 中将文件拆分为多个输出文件?
How to split file into number of output files in Python 3?
我有一个问题陈述:
splitfile(filename,numberoffiles)
A file of 13 lines, split in 3, would have output files of length 4, 4 and 5 if they cannot be evenly distributed. ( Can not have a difference greater than 1 line if they cant be evenly distributed)
我开始学习 python,我必须创建一个函数,将文件拆分为参数中指定的较小文件。
我遇到的问题是我不知道如何处理这种情况,因为它基于文件数量,并且不允许差异大于 1 的概念。
问题的本质(据我了解)是如何确定每个输出文件将包含的行数。这是我为 Python 3.4.3:
想出的
def get_line_counts(total_lines, number_of_files):
base_size = total_lines // number_of_files
line_count_list = [base_size for i in range(number_of_files)]
files_with_an_extra_line = total_lines % number_of_files
for i in range(files_with_an_extra_line):
line_count_list[len(line_count_list) - (i + 1)] += 1
return line_count_list
for i, n in enumerate(get_line_counts(13, 3)):
print("file {0} will contain {1} line(s)".format(i, n))
导致
file 0 will contain 4 line(s)
file 1 will contain 4 line(s)
file 2 will contain 5 line(s)
其余代码只是基本文件 I/O:从输入文本文件读取 n 行并将它们写入输出文本文件。
我有一个问题陈述:
splitfile(filename,numberoffiles)
A file of 13 lines, split in 3, would have output files of length 4, 4 and 5 if they cannot be evenly distributed. ( Can not have a difference greater than 1 line if they cant be evenly distributed)
我开始学习 python,我必须创建一个函数,将文件拆分为参数中指定的较小文件。
我遇到的问题是我不知道如何处理这种情况,因为它基于文件数量,并且不允许差异大于 1 的概念。
问题的本质(据我了解)是如何确定每个输出文件将包含的行数。这是我为 Python 3.4.3:
想出的def get_line_counts(total_lines, number_of_files):
base_size = total_lines // number_of_files
line_count_list = [base_size for i in range(number_of_files)]
files_with_an_extra_line = total_lines % number_of_files
for i in range(files_with_an_extra_line):
line_count_list[len(line_count_list) - (i + 1)] += 1
return line_count_list
for i, n in enumerate(get_line_counts(13, 3)):
print("file {0} will contain {1} line(s)".format(i, n))
导致
file 0 will contain 4 line(s)
file 1 will contain 4 line(s)
file 2 will contain 5 line(s)
其余代码只是基本文件 I/O:从输入文本文件读取 n 行并将它们写入输出文本文件。