繁体   English   中英

将for循环的输出写入多个文件

[英]Write output of for loop to multiple files

我试图读取txt文件的每一行,并打印出不同文件中的每一行。 假设,我有一个文本如下:

How are you? I am good.
Wow, that's great.
This is a text file.
......

现在,我希望filename1.txt具有以下内容:

How are you? I am good.

filename2.txt有:

Wow, that's great.

等等。

我的代码是:

#! /usr/bin/Python

for i in range(1,4): // this range should increase with number of lines 
   with open('testdata.txt', 'r') as input:
       with open('filename%i.txt' %i, 'w') as output:
          for line in input:
            output.write(line)

我得到的是,所有文件都包含文件的所有行。 我希望每个文件只有1行,如上所述。

在for循环中移动第二个with语句,而不是使用外部for循环来计算行数,使用enumerate函数返回一个值及其索引:

with open('testdata.txt', 'r') as input:
  for index, line in enumerate(input):
      with open('filename{}.txt'.format(index), 'w') as output:
          output.write(line)

此外, format的使用通常优先于%字符串格式化语法。

对于如何从线路阅读器获取计数器,这是一个很好的答案。 通常,您需要一个循环来创建文件和读取每一行而不是外部循环创建文件和内部循环读取行。

解决方法如下

#! /usr/bin/Python

with open('testdata.txt', 'r') as input:
    for (counter,line) in enumerate(input):
        with open('filename{0}.txt'.format(counter), 'w') as output:
            output.write(line)

暂无
暂无

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

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