繁体   English   中英

使用Notepad ++将每一行保存为单独的.txt文件

[英]Save each line as separate .txt file using Notepad++

我正在使用Notepad ++来重构一些数据。 每个.txt文件有99行。 我正在尝试运行python脚本来创建99个单行文件。

这是我目前正在运行的.py脚本,我在之前关于该主题的主题中找到了该脚本。 我不确定为什么,但它不是很有效:

    yourfile = open('filename.TXT', 'r')
    counter = 0
    magic = yourfile.readlines()

    for i in magic:
        counter += 1
        newfile = open(('filename_' + str(counter) + '.TXT'), "w")
        newfile.write(i)
        newfile.close()

当我运行这个特定的脚本时,它只是创建一个主机文件的副本,它仍然有99行。

您可能想稍微更改脚本的结构:

with open('filename.txt', 'r') as f:
    for i, line in enumerate(f):
        with open('filename_{}.txt'.format(i), 'w') as wf:
            wf.write(line)

在这种格式中,您可以依靠上下文管理器来关闭文件处理程序,而且您不必单独阅读内容,还有更好的逻辑流程。

您可以使用以下代码来实现此目的。 这是评论,但随意问。

#reading info from infile with 99 lines
infile = 'filename.txt'

#using context handler to open infile and readlines
with open(infile, 'r') as f:
    lines = f.readlines()

#initializing counter
counter = 0

#for each line, create a new file and write line to it.
for line in lines:

    #define outfile name
    outfile = 'filename_' + str(counter) + '.txt'

    #create outfile and write line
    with open(outfile, 'w') as g:
        g.write(line)

    #add +1 to counter
    counter += 1
magic = yourfile.readlines(99)

请尝试像这样删除'99'。

magic = yourfile.readlines()

我试了一下,我有99个文件,每个文件只有一行。

暂无
暂无

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

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