在所有特定名称子目录中运行Python脚本
我有一个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
但是这个方法没有成功,我不知道为什么。在循环中的grep
是为了只获取那些包含.txt文件的文件夹,并对它们运行脚本。
在%a和%t之间加了一行空行,是因为我想自定义Python脚本的输出,让每两个变量之间有一个空行。
我哪里做错了呢?
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")