将命令应用于 python 中的文件列表

apply command to list of files in python

我有一个棘手的问题。我需要将名为 xRITDecompress 的特定命令应用于扩展名为 -C_ 的文件列表,我应该使用 Python.

来执行此操作

不幸的是,此命令不适用于通配符,我无法执行以下操作:

os.system("xRITDecompress *-C_")

原则上,我可以编写一个带有 for 循环的辅助 bash 脚本,并在我的 python 程序中调用它。但是,我不想依赖辅助文件...

在 python 程序中执行此操作的最佳方法是什么?

您可以使用 glob.glob() 获取您想要对其执行 运行 命令的文件列表,然后对于该列表中的每个文件,运行 命令 -

import glob
for f in glob.glob('*-C_'):
    os.system('xRITDecompress {}'.format(f))

来自documentation -

The glob module finds all the pathnames matching a specified pattern according to the rules used by the Unix shell.

如果通过 _(下划线),你想匹配单个字符,你应该使用 -? 来代替,比如 -

glob.glob('*-C?')

请注意,glob 只会在当前目录中搜索,但根据您对原始试用版的要求,似乎这可能是您想要的。


您可能还想看看 subprocess 模块,它是 运行ning 命令(生成进程)的更强大的模块。例子-

import subprocess
import glob
for f in glob.glob('*-C_'):
    subprocess.call(['xRITDecompress',f])

您可以使用 glob.glob or glob.iglob 获取与给定模式匹配的文件:

import glob

files = glob.iglob('*-C_')
for f in files:
    os.system("xRITDecompress %s" % f)

只需使用glob.glob搜索和os.system执行

import os
from glob import glob
for file in glob('*-C_'):
    os.system("xRITDecompress %s" % file)

希望能解决你的问题