【问题标题】:Python - Read Multiple Files & Write To Multiple New FilesPython - 读取多个文件并写入多个新文件
【发布时间】:2021-01-23 12:47:08
【问题描述】:

我知道那里有很多关于阅读和写作的内容,但我仍然没有完全找到我需要的具体内容。

我有 5 个文件(即 in1.txt、in2.txt、in3.txt....),我想打开/读取,通过我拥有的函数运行数据,然后输出新的返回值到相应的新文件(即out1.txt、out2.txt、out3.txt....)

我想在一个程序运行中做到这一点。我不确定如何编写循环来一次处理所有编号的文件。

【问题讨论】:

  • 您希望所有文件并行处理还是一个一个处理?
  • 最简单的。它只需要在文件/程序的一次运行中

标签: python io readfile writefile


【解决方案1】:

如果你希望它们被串行处理,你可以使用如下的for循环:

inpPrefix = "in"
outPrefix = "out"
for i in range(1, 6):
    inFile = inPrefix + str(i) + ".txt"
    with open(inFile, 'r') as f:
        fileLines = f.readlines()

    # process content of each file
    processedOutput = process(fileLines)

    #write to file
    outFile = outPrefix + str(i) + ".txt"
    with open(outFile, 'w') as f:
         f.write(processedOutput)

注意:这假设输入和输出文件与脚本位于同一目录中。

【讨论】:

  • 什么是“行()”?它应该是readline()吗? readlines()?
  • 是的,我已经更新为readlines()
  • 哦,好的,谢谢,最后我感到困惑的是“process(fileLines)”,什么是“process()”?
  • 这是你添加的描述run the data through a function I have的占位符方法。
  • 知道了,谢谢!最后要修复的事情(对于将来发现此问题的其他人),从底部开始的第二行应该是 with open(outFile, 'w')inFile 来做我需要的这个用例!谢谢!
【解决方案2】:

如果您只想单独运行,您可以这样做:

import os

count = 0
directory = "dir/where/your/files/are/"
for filename in os.listdir(directory):
    if filename.endswith(".txt"):
        count += 1
        with open(directory + filename, "r") as read_file:
            return_of_your_function = do_something_with_data()
        with open(directory + count + filename, "w") as write_file:
            write_file.write(return_of_your_function)

【讨论】:

  • 如果是同一个目录呢?这如何从 1-5 创建“out1.txt”文件?
【解决方案3】:

来,你走!我会做这样的事情:
(假设所有输入的 .txt 文件都在同一个输入文件夹中)

input_path  = '/path/to/input/folder/'
output_path = '/path/to/output/folder/'

for count in range(1,6):
    input_file  = input_path  + 'in'  + str(count) + '.txt'
    output_file = output_path + 'out' + str(count) + '.txt'


    with open(input_file, 'r') as f:
        content = f.readlines() 
        output  = process_input(content)
    
    with open(output_file, 'w') as f:
        w.write(output)

【讨论】:

    猜你喜欢
    • 2015-05-23
    • 1970-01-01
    • 2020-04-26
    • 1970-01-01
    • 1970-01-01
    • 2020-10-06
    • 1970-01-01
    • 1970-01-01
    • 2020-09-14
    相关资源
    最近更新 更多