【问题标题】:Directory contents in a list列表中的目录内容
【发布时间】:2014-02-13 02:35:30
【问题描述】:

我试图弄清楚如何在 python 中编写一个脚本,在其中我用“ls”列出当前目录的内容,然后将 ls 的结果放入一个列表中,以便我可以对其中的每一个做一些事情ls中的元素。实际上,我首先尝试在我的终端中执行此操作,然后我将使用 python 编写脚本,但我什至无法让它在我的终端中运行。

哦,我已经尝试将 ls 的输出重定向到一个文件中,但我似乎没有这样做的权限:

>>> subprocess.call(["ls ", directory_expanded, " > ", "namesoutput.txt"])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.6/subprocess.py", line 478, in call
    p = Popen(*popenargs, **kwargs)
  File "/usr/lib64/python2.6/subprocess.py", line 642, in __init__
    errread, errwrite)
  File "/usr/lib64/python2.6/subprocess.py", line 1234, in _execute_child
    raise child_exception
OSError: [Errno 13] Permission denied

【问题讨论】:

    标签: python linux unix command-line io-redirection


    【解决方案1】:

    os.listdir怎么样?

    In [25]: os.listdir('.')
    Out[25]: ['blah']
    

    【讨论】:

    • 这是最有前途的方法。 +1
    【解决方案2】:

    subprocess.check_output 应该适用于标准库中未提供的任何内容。要列出目录,只需使用 os.listdir

    http://docs.python.org/2/library/subprocess.html#subprocess.check_output

    【讨论】:

      猜你喜欢
      • 2014-03-29
      • 2013-12-07
      • 2011-06-10
      • 2010-12-16
      • 2019-02-27
      • 2011-05-14
      • 2011-12-17
      • 1970-01-01
      • 2013-08-04
      相关资源
      最近更新 更多