Python - 读取多个文件并写入多个新文件
Python - Read Multiple Files & Write To Multiple New Files
我知道那里有很多关于阅读和写作的内容,但我仍然没有找到我需要的内容。
我有 5 个文件(即 in1.txt、in2.txt、in3.txt...),我想 open/read、运行通过我拥有的函数获取数据,然后将新的返回值输出到相应的新文件中(即out1.txt、out2.txt、out3.txt...)
我想在一个程序中做到这一点 运行。我不确定如何编写循环来处理一个 运行.
中的所有编号文件
如果您只是逐一查找 运行,您可以执行以下操作:
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)
如果你希望它们被串行处理,你可以使用如下的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)
注意:这假定输入和输出文件与脚本位于同一目录中。
给你!我会做这样的事情:
(假设所有输入的 .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)
我知道那里有很多关于阅读和写作的内容,但我仍然没有找到我需要的内容。
我有 5 个文件(即 in1.txt、in2.txt、in3.txt...),我想 open/read、运行通过我拥有的函数获取数据,然后将新的返回值输出到相应的新文件中(即out1.txt、out2.txt、out3.txt...)
我想在一个程序中做到这一点 运行。我不确定如何编写循环来处理一个 运行.
中的所有编号文件如果您只是逐一查找 运行,您可以执行以下操作:
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)
如果你希望它们被串行处理,你可以使用如下的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)
注意:这假定输入和输出文件与脚本位于同一目录中。
给你!我会做这样的事情:
(假设所有输入的 .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)