python中的文件附加

2024-09-27 00:14:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我在location/root中有n个文件,如下所示

result1.txt
abc
def

result2.txt
abc
def
result3.txt
abc
def

等等。 我必须创建一个名为结果.txt将所有结果文件中的所有值串联起来,循环通过location/root/samplepath中的n个文件。你知道吗


Tags: 文件txtdeflocationrootabcresult1result2
2条回答

这可能是一个简单的方法

比如说我的文件脚本.py在一个文件夹中,与该脚本一起有一个名为testing的文件夹,其中包含所有文本文件,如file\u 0,file\u 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可能更容易。如果必须用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")

相关问题 更多 >

    热门问题