2014-06-09 52 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)