【问题标题】:process a directory of files using python使用python处理文件目录
【发布时间】:2013-08-21 14:06:34
【问题描述】:

我有一个目录,我想选择该目录中的每个文件并在其上运行 python 代码: 所以我做了以下

for file in os.listdir('/Users/Desktop/Xfiles'):
     os.system('/sw/bin/python2.7 pythonCode.py /Users/Desktop/Xfiles/file')

这不起作用,我想处理 listdir 中的“文件”....我该怎么做?

【问题讨论】:

  • 我认为当 Python 来自 Perl 或 Bash 等允许您将变量放在引号内的语言时,这是一个常见的错误。您能否将标题更改为与您遇到的实际问题有关的内容,以便其他新用户可以找到它?类似于“如何将 Python 变量插入到带引号的字符串中?”

标签: python file operating-system


【解决方案1】:

传递给os.system 的路径是硬编码的。你应该通过filename

dirpath = '/Users/Desktop/Xfiles'
for filename in os.listdir(dirpath):
    os.system('/sw/bin/python2.7 pythonCode.py {}/{}'.format(dirpath, filename))
  • 不要使用file 作为变量名。它会影响内置的 file 函数。

【讨论】:

  • 非常感谢,我花了很多时间试图弄清楚这一点!
【解决方案2】:

你可以用

做字符串插值
file = "myfilename"
"some text {}".format(file)
# white should result in "some text myfilename"

但是对于操纵路径,最好的方法是使用

os.path.join('/Users/gchella1/Desktop/forGeorge/Xfiles/', file)

【讨论】:

    【解决方案3】:

    你忘了把“文件”放在引号里吗?

    for file in os.listdir('/Users/gchella1/Desktop/forGeorge/Xfiles'):
        os.system('/sw/bin/python2.7 pythonCode.py /Users/gchella1/Desktop/forGeorge/Xfiles/'+file)
    

    这对我有用。

    for file in os.listdir('.'):
        os.system('ls '+file)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-26
      • 1970-01-01
      • 2012-02-20
      • 1970-01-01
      • 2014-01-24
      • 2023-03-12
      • 1970-01-01
      相关资源
      最近更新 更多