将for循环的输出写入多个文件 [英] Write output of for loop to multiple files
问题描述
我试图读取 txt
文件的每一行,并在不同的文件中打印出每一行。假设,我有一个像这样的文本文件:
你好吗?我很好。
哇,太好了。
这是一个文本文件。
......
现在,我要 filename1 .txt
有以下内容:
你好吗?我很好。
filename2.txt
p>
哇,太好了。
等等。
我的代码是:
#! / usr / bin / Python
在范围内(1,4)://这个范围应该随着行数
加上open('testdata.txt','r' )作为输入:
以open('filename%i.txt'%i,'w')作为输出:
输入中的行:
output.write(line)
我得到的是,所有的文件都有文件的所有行。我想要每个文件只有一行,如上所述。
在for循环中用语句移动第二个
使用外部循环来计算行数,使用枚举
函数返回一个值AND其索引:
用open('testdata.txt','r')作为输入:
用于索引,枚举(输入):
用open('filename {} .txt'.format(index),'w')as output:
output.write(line)
此外,使用 format
通常优于%
字符串格式化语法。 / p>
I am trying to read each line of a txt
file and print out each line in a different file. Suppose, I have a file with text like this:
How are you? I am good.
Wow, that's great.
This is a text file.
......
Now, I want filename1.txt
to have the following content:
How are you? I am good.
filename2.txt
to have:
Wow, that's great.
and so on.
My code is:
#! /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)
What I am getting is, all the files are having all the lines of the file. I want each file to have only 1 line, as explained above.
解决方案 Move the 2nd with
statement inside your for loop and instead of using an outside for loop to count the number of lines, use the enumerate
function which returns a value AND its index:
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)
Also, the use of format
is typically preferred to the %
string formatting syntax.
这篇关于将for循环的输出写入多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!