【问题标题】:How to run a program on each file in directory [duplicate]如何在目录中的每个文件上运行程序[重复]
【发布时间】:2020-04-02 21:19:40
【问题描述】:

所以我有一个 python 文件file.py。我有一个目录,里面有很多 .txt 文件。所以我想知道如何为目录中的每个txt文件做python3 file.py txt1.txtpython3 file.py txt2.txt等等?

【问题讨论】:

  • 您是否要读取每个带有.txt 扩展名的文件?
  • @midrizi 是的!没错

标签: python python-3.x bash shell


【解决方案1】:

这是使用 find 的替代解决方案:

find /path/to/your/txtfiles/*.txt -type f -exec python3 file.py {} \;

我喜欢 find,因为我认为它可以在匹配特定条件的同时更轻松地递归搜索目录。

这里-type f 只选择常规文件,-exec 正在运行您的脚本,用文件名代替大括号。

【讨论】:

    【解决方案2】:

    只需将 ls 的输出(过滤您想要的文件)输入到 xargs 的标准输入中:

    ❯❯❯ ls *.txt | xargs -I{} python3 file.py {}
    

    【讨论】:

    • 不,don't use ls。在 ls 甚至运行之前,shell 已经扩展了 *.txt。也不需要xargs
    猜你喜欢
    • 2014-10-21
    • 1970-01-01
    • 2016-02-17
    • 2020-11-22
    • 1970-01-01
    • 1970-01-01
    • 2020-01-16
    • 2015-12-19
    • 1970-01-01
    相关资源
    最近更新 更多