0

I have a python script which takes some parameters, and I want to run this script on all the sub directories starting from the one that the script is inside.

The idea is I want to get a custom output of the script to be saved in the file.

here's what i've done:

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

But this is not working and I don't know why. The grep in the for loop is to only get the directories that contains .txt files and apply the script on them.

The new line between %a and %t is because I want to customize the output of the output of the python script to include a new line between each 2 variables

What am I doing wrong ?

4

1 回答 1

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")
于 2013-02-21T15:33:55.337 回答