2013-11-22 50 views
0

我需要从大量来自不同文件夹的txt文件创建摘要文件。我开始用python做,但任何提供的解决方案都很好,即。蟒蛇时,awk,bash的合并来自多个txt文件的结果文件

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") 

也就是说办法,我试过了,但一切都失败有:)

我能想象有更容易的方法可以做到这一点,我还没有听说过。

+1

'id'是内建的方法。从不使用它作为变量 – Farhadix

+0

发布一些示例输入和预期输出。 –

回答

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

可能会更简单:'cat $(find。-name'summary.txt')> grandsummary.txt'。如果有太多争论,“找到。 -name'summary.txt'-print0 | xargs -0 cat> grandsummary.txt'。或者用递归blobbing,'cat **/summary.txt> grandsummary.txt' – xmo

0

如果你看一下代码着色,你的报价是在最后一行不正确。此外,你应该使用os.path API来处理你的东西。并且with为了确保文件被正确关闭。最后,不需要readline,文件是可迭代的行。最后,为什么你要手动重组路径?为什么不只是open(items, 'rb')

0

下面是一个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. 

这是从内存中写的,所以它可能需要一些拉坯。