【问题标题】:How to create 5 small text files from a large text files using python?如何使用 python 从大文本文件创建 5 个小文本文件?
【发布时间】:2021-02-23 19:42:46
【问题描述】:

假设我有一个包含 10 行文本的大文件名 input.txt:

Lorem Ipsum is simply a dummy text of the printing and typesetting
industry. Lorem Ipsum has been the industry's standard dummy text ever
since the 1500s  when an unknown printer took a galley of type and
scrambled it to make a type  specimen book. It has survived not only
five centuries, but also the leap into  electronic typesetting,
remaining essentially unchanged. It was popularised in  the 1960s with
the release of Letraset sheets containing Lorem Ipsum passages,  and
more recently with desktop publishing software like Aldus PageMaker
including  versions of Lorem Ipsum. Contrary to popular belief, Lorem
Ipsum is not simply  random text. It has roots in a piece of classical

我想创建 5 个文本文件,每个文件包含 2 行。像这样的:

./first.txt
Lorem Ipsum is simply a dummy text of the printing and typesetting
industry. Lorem Ipsum has been the industry's standard dummy text ever

./second.txt
since the 1500s  when an unknown printer took a galley of type and
scrambled it to make a type  specimen book. It has survived not only

...并在继续。

有人可以帮帮我吗?

【问题讨论】:

    标签: python python-3.x file-io


    【解决方案1】:

    这是脚本:

    file = open('input.txt', 'r', encoding="utf-8")
    
    Lines = file.readlines()  
    
    count = 0
    i = 0
    string = []
    for line in Lines:
    #     print(line)
        if(count == 2):
            write_file = open(str('input') + str(i) + '.txt', 'w', encoding="utf-8")
            write_file.writelines(string)
            string = []
            i += 1
            count = 0
        else:
            string.append(line)
            count += 1
    

    【讨论】:

    • 回答他自己的帖子应该是指出一些不是棘手、困难或具体的问题,即使一开始对你来说似乎很难,但对我来说它没有t 完全值得在 SO 上发表一篇文章。还有一些更好的方法来做到这一点
    • 另外你的脚本只写了 3 个文件,并且错过了行。所以你的答案甚至不正确
    【解决方案2】:

    一般的方式是

    with open('input.txt', 'r', encoding="utf-8") as fic:
        lines = fic.readlines()
    
    # number of lines per file
    split_size = 2
    
    for idx in range(len(lines) // split_size):
        with open(f"input{idx}.txt", 'w', encoding="utf-8") as fic:
            fic.writelines(lines[idx * split_size:(idx + 1) * split_size])
    

    【讨论】:

      猜你喜欢
      • 2015-01-18
      • 1970-01-01
      • 1970-01-01
      • 2018-08-04
      • 2011-08-12
      • 2019-06-30
      • 2021-09-21
      • 2021-09-17
      相关资源
      最近更新 更多