python中的文件追加
我在location/root中有n个文件,如下所示python中的文件追加,python,Python,我在location/root中有n个文件,如下所示 result1.txt abc def result2.txt abc def result3.txt abc def 等等。 我必须创建一个名为result.txt的合并文件,其中包含从所有结果文件连接而来的所有值,这些结果文件在位置/root/samplepath中循环通过n个文件。正如其他人所建议的那样,使用cat可能更容易。如果您必须使用Python来完成此操作,那么这应该是可行的。它查找目录中的所有文本文件,并将其内容附加到结果
result1.txt
abc
def
result2.txt
abc
def
result3.txt
abc
def
等等。
我必须创建一个名为result.txt的合并文件,其中包含从所有结果文件连接而来的所有值,这些结果文件在位置/root/samplepath中循环通过n个文件。正如其他人所建议的那样,使用cat可能更容易。如果您必须使用Python来完成此操作,那么这应该是可行的。它查找目录中的所有文本文件,并将其内容附加到结果文件中
import glob, os
os.chdir('/root')
with open('result.txt', 'w+') as result_file:
for filename in glob.glob('result*.txt'):
with open(filename) as file:
result_file.write(file.read())
# append a line break if you want to separate them
result_file.write("\n")
这可能是一个简单的方法 例如,让我们说我的文件script.py位于一个文件夹中,与该脚本一起还有一个名为testing的文件夹,其中所有的文本文件都命名为file_0、file_1
import os
#reads all the files and put everything in data
number_of_files = 0
data =[]
for i in range (number_of_files):
fn = os.path.join(os.path.dirname(__file__), 'testing/file_%d.txt' % i)
f = open(fn, 'r')
for line in f:
data.append(line)
f.close()
#write everything to result.txt
fn = os.path.join(os.path.dirname(__file__), 'result.txt')
f = open(fn, 'w')
for element in data:
f.write(element)
f.close()
可能重复的
cat result?.txt>result.txt
?到目前为止您有没有尝试过?为什么不使用cat?如果目录中有其他txt文件怎么办。如果我使用这个glob,那么所有的txt文件都将被连接起来?如果您只想要包含result
关键字的文件,请执行glob.glob('result*.txt')
。