[英]process a directory of files using python
I have a directory and I want to pick every file within that directory and run a python code on it: So I do the following 我有一个目录,我想选择该目录中的每个文件并在其上运行python代码:所以我执行以下操作
for file in os.listdir('/Users/Desktop/Xfiles'):
os.system('/sw/bin/python2.7 pythonCode.py /Users/Desktop/Xfiles/file')
This does not work, I want to process the "file" from the listdir....how can I do that? 这不起作用,我想从列表目录中处理“文件”。...我该怎么做?
The path passed to the os.system
is hard coded. 传递给
os.system
的路径是硬编码的。 You should pass filename
. 您应该传递
filename
。
dirpath = '/Users/Desktop/Xfiles'
for filename in os.listdir(dirpath):
os.system('/sw/bin/python2.7 pythonCode.py {}/{}'.format(dirpath, filename))
You can do string interpolation with 您可以使用
file = "myfilename"
"some text {}".format(file)
# white should result in "some text myfilename"
But for manipulating paths, the best way is to use 但是对于操纵路径,最好的方法是使用
os.path.join('/Users/gchella1/Desktop/forGeorge/Xfiles/', file)
did you forget to put "file" out of the quotes ? 您是否忘了在引号中加上“文件”?
for file in os.listdir('/Users/gchella1/Desktop/forGeorge/Xfiles'):
os.system('/sw/bin/python2.7 pythonCode.py /Users/gchella1/Desktop/forGeorge/Xfiles/'+file)
this works for me. 这对我有用。
for file in os.listdir('.'):
os.system('ls '+file)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.