简体   繁体   English

将for循环的输出写入多个文件

[英]Write output of for loop to multiple files

I am trying to read each line of a txt file and print out each line in a different file. 我试图读取txt文件的每一行,并打印出不同文件中的每一行。 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: 现在,我希望filename1.txt具有以下内容:

How are you? I am good.

filename2.txt to have: filename2.txt有:

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. 我希望每个文件只有1行,如上所述。

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

Also, the use of format is typically preferred to the % string formatting syntax. 此外, format的使用通常优先于%字符串格式化语法。

Here is a great answer, for how to get a counter from a line reader. 对于如何从线路阅读器获取计数器,这是一个很好的答案。 Generally, you need one loop for creating files and reading each line instead of an outer loop creating files and an inner loop reading lines. 通常,您需要一个循环来创建文件和读取每一行而不是外部循环创建文件和内部循环读取行。

Solution below. 解决方法如下

#! /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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM