在具有特定名称的所有子目录上运行python脚本 [英] Run python script on all subdirectories with specific name

查看:50
本文介绍了在具有特定名称的所有子目录上运行python脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带一些参数的python脚本,我想在脚本所在的所有子目录中运行此脚本.

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.

这是我所做的:

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文件的目录,并将脚本应用于这些目录.

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.

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

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

我在做什么错了?

推荐答案

如果要在脚本所在的所有子目录中运行此脚本,请尝试执行此操作而是这样:

If you want to run this script on all the sub directories starting from the one that the script is inside, then try doing it this way instead:

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[]

如果您的原始代码是这样的:

If your original code was this:

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

然后您将其更改为类似这样的内容:

then you just alter it to something like this:

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

这篇关于在具有特定名称的所有子目录上运行python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆