Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ruby-on-rails-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在目录中的每个文件上运行程序_Python_Python 3.x_Bash_Shell - Fatal编程技术网

Python 如何在目录中的每个文件上运行程序

Python 如何在目录中的每个文件上运行程序,python,python-3.x,bash,shell,Python,Python 3.x,Bash,Shell,所以我有一个python文件file.py。我有一个目录,其中有许多.txt文件。因此,我想知道如何对目录中的每个txt文件执行python3 file.py txt1.txt,python3 file.py txt2.txt等操作?只需将ls(过滤所需文件)的输出导入xargs的stdin即可: 以下是使用“查找”的替代解决方案: find /path/to/your/txtfiles/*.txt -type f -exec python3 file.py {} \; 我喜欢find,因为我

所以我有一个python文件
file.py
。我有一个目录,其中有许多
.txt
文件。因此,我想知道如何对目录中的每个txt文件执行
python3 file.py txt1.txt
python3 file.py txt2.txt
等操作?

只需将ls(过滤所需文件)的输出导入xargs的stdin即可:


以下是使用“查找”的替代解决方案:

find /path/to/your/txtfiles/*.txt -type f -exec python3 file.py {} \;
我喜欢find,因为我认为它使递归搜索目录更容易,同时匹配特定条件


此处
-type f
仅选择常规文件,而
-exec
正在运行脚本,文件名被替换为大括号。

您是否尝试读取扩展名为
.txt
的所有文件?@midrizi是!那是正确的,不。shell在
ls
运行之前已经展开了
*.txt
。那么也不需要
xargs
find /path/to/your/txtfiles/*.txt -type f -exec python3 file.py {} \;