使用Python按行号将大文本文件拆分为较小的文本文件 [英] Splitting large text file into smaller text files by line numbers using Python

查看:30
本文介绍了使用Python按行号将大文本文件拆分为较小的文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本文件,内容为really_big_file.txt,其中包含:

I have a text file say really_big_file.txt that contains:

line 1
line 2
line 3
line 4
...
line 99999
line 100000

我想编写一个 Python 脚本,将really_big_file.txt 分成每个300 行的小文件.例如,small_file_300.txt 包含第 1-300 行,small_file_600 包含第 301-600 行,依此类推,直到有足够的小文件来包含大文件中的所有行.

I would like to write a Python script that divides really_big_file.txt into smaller files with 300 lines each. For example, small_file_300.txt to have lines 1-300, small_file_600 to have lines 301-600, and so on until there are enough small files made to contain all the lines from the big file.

对于使用 Python 完成此操作的最简单方法的任何建议,我将不胜感激

I would appreciate any suggestions on the easiest way to accomplish this using Python

推荐答案

lines_per_file = 300
smallfile = None
with open('really_big_file.txt') as bigfile:
    for lineno, line in enumerate(bigfile):
        if lineno % lines_per_file == 0:
            if smallfile:
                smallfile.close()
            small_filename = 'small_file_{}.txt'.format(lineno + lines_per_file)
            smallfile = open(small_filename, "w")
        smallfile.write(line)
    if smallfile:
        smallfile.close()

这篇关于使用Python按行号将大文本文件拆分为较小的文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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