合并来自多个txtfiles的结果文件

2024-10-04 03:21:08 发布

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

我需要从不同文件夹的大量txt文件中创建一个摘要文件。我开始用python来做,但是提供的任何解决方案都很好,比如python、awk、bash

find = "find -name \"summary.txt\" > output.txt"
os.system(find)

o = open("output.txt", "r")
read = o.readlines()
for items in read:
    pilko = items.split("/")
    id = pilko[1]

我需要从子文件夹中搜索摘要文件,并将txt文件的结果编译为结果文件。我有点困在这里如何在for循环中打开txt文件,将数据保存到结果文件并继续。你知道吗

plate = pilko[4]
print id+"/"+pilko[2]+"/"+pilko[3]+"/"+plate+"/"+pilko[5]
foo = open("id+"/"+pilko[2]+"/"+pilko[3]+"/"+plate+"/"+pilko[5]", "r")

这就是我尝试过的方法,但一切都失败了:)

我可以想象有更简单的方法来做到这一点,我还没有听说。你知道吗


Tags: 文件方法txt文件夹idforreadoutput
3条回答

如果你看代码的颜色,你的报价是不正确的最后一行。此外,您可能应该使用操作系统路径你的东西的API。和with以确保文件正确关闭。最后,不需要readline,一个文件是一个行的iterable。最后,为什么要手动重新组合路径?为什么不干脆open(items, 'rb')?你知道吗

for f in `find -name 'summary.txt' -print` ; do cat $f >> /tmp/grandsummary.txt ; done

下面是一个python解决方案:

import os
with open('/path/to/result/file.txt', 'wb') as result_file:
    for root, dirs, files in os.walk('/path/to/start/directory'):  # walk the file system
        if 'file_name_I_want.txt' in files:  # This folder has the file i'm looking for!
            with open(os.path.join(root, 'file_name_I_want.txt'), 'rb') as src_file:  # open it up
                result_file.write(src_file.read())  # Read from src, store in dest.

这是从内存中写的,所以可能需要一些修改。你知道吗

相关问题 更多 >