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

use*_*422 2 python file-io file

我试图读取txt文件的每一行,并打印出不同文件中的每一行.假设,我有一个文本如下:

How are you? I am good.
Wow, that's great.
This is a text file.
......
Run Code Online (Sandbox Code Playgroud)

现在,我希望filename1.txt有以下内容:

How are you? I am good.
Run Code Online (Sandbox Code Playgroud)

filename2.txt 具有:

Wow, that's great.
Run Code Online (Sandbox Code Playgroud)

等等.

我的代码是:

#! /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)
Run Code Online (Sandbox Code Playgroud)

我得到的是,所有文件都包含文件的所有行.我希望每个文件只有1行,如上所述.

Bee*_*ise 8

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)
Run Code Online (Sandbox Code Playgroud)

此外,使用format通常优先于%字符串格式化语法.