简体   繁体   English

使用python处理文件目录

[英]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))
  • Don't use file as variable name. 不要将file用作变量名。 It shadows builtin file function. 它隐藏了内置file功能。

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.

相关问题 Python,处理目录中的文件是否安全? - Python, is it safe to process files in a directory? 使用 python os.walk 如何检查目录名并仅处理特定目录中的那些文件(递归)? - Using python os.walk how to check for directory name and only process those files (recursively) in the specific directory? 如何使用Python将文件从一个子文件夹处理到每个目录中的另一个子文件夹? - How to process files from one subfolder to another in each directory using Python? Python->复制目录,而另一个进程从/向其中删除/添加文件 - Python -> Copy directory while another process removes/adds files from/to it 如何列出目录中的文件并逐一处理? -Python - how to make list of files in directory and process them one by one? - Python 使用多进程同时在python中下载文件 - Concurrently downloading files in python using multi process 使用python生成器处理大型文本文件 - using a python generator to process large text files python 使用多进程处理文件的问题 - python Problems with using multiple processes to process files 如何使用python处理hdfs中的文件 - How to process the files in hdfs using python 使用python修改目录中的多个.xml文件 - Modify mutliple .xml files in a directory using python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM