Python 将for循环的输出写入多个文件
我试图读取Python 将for循环的输出写入多个文件,python,file,file-io,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 rang
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)
我得到的是,所有的文件都有文件的所有行。我希望每个文件只有一行,如上所述 在for循环中使用语句移动第二个
,使用枚举
函数返回值及其索引,而不是使用外部for循环来计算行数:
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)
另外,使用格式
通常优于%
字符串格式语法。通常,创建文件和读取每行需要一个循环,而不是创建文件的外部循环和读取行的内部循环
解决方案如下
#! /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)