Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 组合来自多个txt文件的结果文件_Python_Bash_Awk - Fatal编程技术网

Python 组合来自多个txt文件的结果文件

Python 组合来自多个txt文件的结果文件,python,bash,awk,Python,Bash,Awk,我需要从不同文件夹的大量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 =

我需要从不同文件夹的大量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")
这是我尝试过的方法,但一切都失败了:)


我可以想象有更简单的方法来实现这一点,但我还没有听说。

如果您查看代码的颜色,您在最后一行中的引用是不正确的。此外,您可能应该为您的东西使用os.path API。使用和
,以确保文件正确关闭。最后,无需
readline
,一个文件就是一个可编辑的行。最后,为什么要手动重新组合路径?为什么不打开(items,'rb')

这里有一个python解决方案:

for f in `find -name 'summary.txt' -print` ; do cat $f >> /tmp/grandsummary.txt ; done
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.

这是从内存中写入的,因此可能需要一些修改。

id
是一种内置方法。永远不要将其用作变量发布一些示例输入和预期输出。可以更简单:
cat$(find.-name'summary.txt')>grandsummary.txt
。如果参数太多,
find-名称'summary.txt'-print0 | xargs-0 cat>grandsummary.txt
。或者使用递归blobbing,
cat**/summary.txt>grandsummary.txt