[英]Run python script on all subdirectories with specific name
我有一個帶一些參數的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個變量之間包含一條新行
我究竟做錯了什么 ?
如果要從腳本所在的子目錄開始在所有子目錄上運行此腳本 ,請嘗試以這種方式進行操作:
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")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.