我正在嘗試讀取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)
我所得到的是,所有的文件都具有文件的所有行。如上所述,我希望每個文件只有一行。