【问题标题】:Read all files in a folder and also the filenames in python? [duplicate]读取文件夹中的所有文件以及python中的文件名? [复制]
【发布时间】:2013-12-25 05:37:51
【问题描述】:

如何读取所有文件以及文件名? 我正在使用 MAC,那么有没有其他方法可以在 Python 中为 MAC 提供路径?

【问题讨论】:

  • Mac 只是 POSIX 系统,与 Linux 相同。 OS X 没有不同的路径处理方式。到目前为止,您自己尝试过什么?你见过os.listdir() 了吗?
  • 嗯..我很确定你可以很容易地用谷歌搜索这个..
  • import glob path = '/folder/' files=glob.glob(path) cnt=0 for htmlfile in files: f=open(htmlfile).read() print cnt f.readlines() cnt=cnt+1 f.close()
  • 我已经给出了相对路径

标签: python


【解决方案1】:

也许是这样的?或者如果你不需要递归,os.listdir() 会更简单。

即使在 Windows 上,如果使用得当,Python 也会抽象出操作系统之间的差异。

#!/usr/local/cpython-3.3/bin/python

import os

def main():
    for root, dirs, files in os.walk('/home/dstromberg/src/outside-questions'):
        for directory in dirs:
            print('directory', os.path.join(root, directory))
        for file_ in files:
            print('file', os.path.join(root, file_))

main()

请参阅http://docs.python.org/3/library/os.html 了解更多信息。

【讨论】:

    猜你喜欢
    • 2010-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-07
    • 1970-01-01
    • 1970-01-01
    • 2018-07-28
    相关资源
    最近更新 更多