如何在Python 3中将文件拆分为多个输出文件? [英] How to split file into number of output files in Python 3?

查看:310
本文介绍了如何在Python 3中将文件拆分为多个输出文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题说明:

splitfile(文件名,数字offiles)

一个13行的文件(一分为三),如果不能均匀分布,则输出文件的长度为4、4和5. (如果它们不能均匀分布,则相差不能大于1行)

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,我必须创建一个函数来将文件拆分为参数中指定的较小文件.

I started learning python and I have to create a function that will split a file into smaller ones as specified in the parameters.

我遇到的麻烦是我不知道如何处理这种情况,因为它基于文件数,并且不允许大于1的差异.

The thing I am having trouble with is I do not know how to approach this scenario due to it being based off of number of files and the concept of having a difference greater than 1 being non permissible.

推荐答案

问题的实质(据我所知)是如何确定每个输出文件将包含的行数.这是我为Python 3.4.3设计的:

The essence of the question (as I understand it) is how to determine the number of lines that each output file will contain. This is what I came up with for 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 行并将它们写入输出文本文件.

The rest of the code would just be basic file I/O: read n lines from an input text file and write them to an output text file.

这篇关于如何在Python 3中将文件拆分为多个输出文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆