【问题标题】:Python loop over files in directory then listPython循环遍历目录中的文件然后列出
【发布时间】:2016-12-24 02:17:05
【问题描述】:

我正在尝试遍历目录中的文件并列出每个文件的路径。 我的代码遍历每个文件,但列出了错误的目录。返回完整目录我缺少什么?

到目前为止,这是我的代码:

import os

directory = "posts/"

for file in os.listdir(directory):
    if file.endswith(".md"):
        dir = os.path.abspath(file)
        print "The Path is: " + str(dir)

结构是这样的:

.
├── app.py
└── posts
    ├── first.md
    └── second.md

来自终端的输出(缺少目录的/posts/ 部分):

The Path is: /home/tc/user/python-md-reader/second.md
The Path is: /home/tc/user/python-md-reader/first.md

【问题讨论】:

    标签: python loops


    【解决方案1】:

    如果你看一下源代码:

    def abspath(path):
        """Return the absolute version of a path."""
        if not isabs(path):
            if isinstance(path, unicode):
                cwd = os.getcwdu()
            else:
                cwd = os.getcwd()
            path = join(cwd, path)
        return normpath(path)         # normpath according to the comment 
                                      # """Normalize path, eliminating double slashes, etc."""
    

    abspath 所做的只是将当前工作目录与您提供的path 连接起来,因为您只提供文件作为路径,并且您是posts 目录的上一级,它将被忽略。

    【讨论】:

      【解决方案2】:

      你可以把目录放回路径:

      dir = os.path.abspath(os.path.join(directory, file))
      

      【讨论】:

      • 这解决了我眼前的问题,谢谢。我不确定为什么 abspath 方法返回我的 app.py 文件的根目录而不是帖子目录
      • @c4binever:我认为您认为abspath 会“找到一个文件”,但实际上它只是采用您提供的路径并相对于当前目录“扩展”它。由于您当前的目录是 . 而不是 ./directory,因此它没有按照您的意愿行事。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-25
      • 1970-01-01
      • 1970-01-01
      • 2020-11-05
      相关资源
      最近更新 更多