使用记事本将每行保存为单独的.txt文件++

2024-06-16 13:28:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用记事本++来重组一些数据。每个.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行。在


Tags: 文件数据pytxt脚本主题magiccounter
3条回答

您可能需要稍微更改一下脚本的结构:

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”。在

^{pr2}$

我试过了,我有99个文件,每个文件都有一行。在

相关问题 更多 >