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

时间:2014-06-09 12:03:28

标签: python file file-io

我正在尝试读取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行,如上所述。

2 个答案:

答案 0 :(得分:8)

在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的使用通常优先于%字符串格式化语法。

答案 1 :(得分:1)

Here is a great answer, for how to get a counter from a line reader.通常,您需要一个循环来创建文件并读取每一行而不是外部循环创建文件和内部循环读取行。

以下解决方案。

#! /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)