【问题标题】:Write output of for loop to multiple files将for循环的输出写入多个文件
【发布时间】:2014-07-29 23:18:43
【问题描述】:

我正在尝试读取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)

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

【问题讨论】:

    标签: python file file-io


    【解决方案1】:

    将第二个 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)
    

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

    【讨论】:

      【解决方案2】:

      Here is a great answer, for how to get a counter from a line reader. 通常,创建文件和读取每一行需要一个循环,而不是创建文件的外循环和读取行的内循环。

      下面的解决方案。

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

      【讨论】:

        猜你喜欢
        • 2017-06-19
        • 2020-08-08
        • 2017-08-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多