简体   繁体   English

如何逐行保存文本文件(使用python或其他编辑器)

[英]How to save text file line by line (using python or other editors)

I have a text file with 600 lines(\n), and I want to make 600 text files saving each line.我有一个包含 600 行 (\n) 的文本文件,我想制作 600 个文本文件来保存每一行。 So I want to write text files line by line, but I don't know how I can make it.所以我想逐行写文本文件,但我不知道我该怎么做。

eg If I have 'all.txt' file with 600 lines, like: line1 aaaaaa line2 bbbbbb line3 cccccc... line 600 zzzzzz例如,如果我有 600 行的“all.txt”文件,例如:line1 aaaaaa line2 bbbbbb line3 cccccc... line 600 zzzzzz

-> I want to make results like this: 1.txt (content: aaaaaa) 2.txt (content: bbbbbb) 3.txt (content: cccccc)... 600.txt (content: zzzzzz) -> 我想得到这样的结果: 1.txt (内容: aaaaaa) 2.txt (内容: bbbbbb) 3.txt (内容: cccccc)... 600.txt (内容: zzzzzz)

I have python and notepad++, so it would be really nice to make these results using them.我有 python 和 notepad++,所以使用它们制作这些结果真的很棒。 Thank you so much:)太感谢了:)

This is what I tried, but the result was just 'i.txt' file with the last 600th line saved.这是我尝试过的,但结果只是保存了最后 600 行的“i.txt”文件。

with open('all.txt',encoding='utf-8') as f:
    content = f.readlines()
len(content)
600
for i, line in enumerate(content):
    with open('i.txt', 'w') as f:
        f.write(content[i])
with open('all.txt') as f:
    for i, line in enumerate(f, 1):
        with open(f'{i}.txt', 'w') as f2:
            f2.write(line)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM