在具有特定名称的所有子目录上运行python脚本

时间:2013-02-21 15:03:15

标签: python bash

我有一个python脚本,它接受一些参数,我想在脚本所在的所有子目录上运行这个脚本。

我的想法是希望获得要保存在文件中的脚本的自定义输出。

这就是我所做的:

for x in `find . -type d | grep data`;
do
python /full/path/to/file/script.py -f "%a
%t" $x/*.txt -o $x/res.txt
done

但这不起作用,我不知道为什么。 for循环中的grep只是获取包含.txt文件的目录并在其上应用脚本。

%a和%t之间的新行是因为我想自定义python脚本输出的输出,以在每个2个变量之间包含一个新行

我做错了什么?

1 个答案:

答案 0 :(得分:0)

如果您希望在脚本所在的所有子目录中运行此脚本,那么请尝试这样做:

import os

for path, directories, files in os.walk(os.path.dirname(os.path.realpath(__file__))):
    print path, directories, files
    txt_files = [arbitrary_file for arbitrary_file in files if arbitrary_file[-4:].lower() == ".txt"]

    #run your python here
    txt_files = [txt_file for arbitrary_file in files if arbitrary_file[]

如果您的原始代码是:

import sys

text_files_to_process = #Do Something with sys.argv - or whatever you're using to parse your arguments.

with open("res.txt", "w") as f:
    #do something with all the text files, and write the output to res.txt.
    for text_file in text_files_to_process:
        with open(text_file) as tf:
            for line in tf:
                #whatever your text processing is
            tf.write("something")

然后你只需改成它:

import os

for path, directories, files in os.walk(os.path.dirname(os.path.realpath(__file__))):
    print path, directories, files
    txt_files = [arbitrary_file for arbitrary_file in files if arbitrary_file[-4:].lower() == ".txt"]

    txt_files = [txt_file for arbitrary_file in files if arbitrary_file[]

    with open("res.txt", "w") as f:
        #do something with all the text files, and write the output to res.txt.
        for text_file in txt_files:
            with open(text_file) as tf:
                for line in tf:
                    #whatever your text processing is
                tf.write("something")