修改Python脚本以在目录中的每个文件上运行
我有一个Python脚本,它可以接受文件名作为命令参数,然后处理这个文件。不过,因为我有263个文件需要进行相同的处理,我在想是否可以用一个for循环来修改命令参数部分,这样就能依次处理文件夹里的所有文件了?谢谢,Sat
编辑:
这里是系统参数的代码:
try:
opt_list, args = getopt.getopt(sys.argv[1:], 'r:vo:A:Cp:U:eM:')
except getopt.GetoptError, msg:
print 'prepare_receptor4.py: %s' %msg
usage()
sys.exit(2)
其中'r'是需要处理的文件名,其他的参数是可选的。我不太确定怎么用for循环来修改这个部分。
5 个回答
4
os.walk()
听起来可能适合这个情况。
def traverse_and_touch(directory, touch):
'''
General function for traversing a local directory. Walks through
the entire directory, and touches all files with a specified function.
'''
for root, dirs, files in os.walk(directory):
for filename in files:
touch(os.path.join(root, filename))
return
现在,你只需要传入你想要遍历的文件夹和一个函数,它就会对每个文件执行这个函数。
os.walk()
还会遍历所有的子文件夹。
5
当我在处理多个文件或文件夹时,我通常会使用 os.walk 这个工具:
import os
for root, dirs, files in os.walk(dir):
for fname in files:
do_something(fname)
你可以通过 getopt 或 optparse 来获取你的目录。如果需要的话,你还可以使用 os.path.abspath 来构建绝对路径。
current_file = "%s%s%s" % (os.path.abspath(root), os.path.sep, fname)
do_something(current_file)
15
实际上,不管你用的是哪个命令行工具,它们通常都有一些简单的语法可以用来实现这个功能。比如在Bash中,你可以这样写:
for f in *; do python myscript.py $f; done
如果你想在Python中实现这个功能,我建议你把主要代码放在一个函数里,这个函数需要一个参数,就是文件名。
def process(filename):
...code goes here...
然后你可以这样调用这个函数:
for f in os.listdir(folder):
process(f)
folder
可以作为命令行参数传入,或者直接写在脚本里(如果这个文件夹名不是你会重复使用的)。
编辑:针对你的修改,我建议直接把文件名作为普通的命令行参数传入,不用使用 -r
选项,这样它们就会放在 args
里。然后你可以这样做:
for f in args:
process(f)
或者如果你更想把目录名作为命令行参数传入的话,
for d in args:
for f in os.listdir(d):
process(f)
另外,我想你也可以传入多个 -r
选项,然后这样做:
for opt, arg in opt_list:
if opt == '-r':
process(arg)