2014-06-09 49 views
2

我正在尝试读取txt文件的每一行,并在不同的文件中打印出每一行。假设,我有这样的文本文件:将for循环的输出写入多个文件

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) 

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

回答

7

移动第二with语句中的for循环和,而不是使用外部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

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)