简体   繁体   English

Python循环遍历目录中的文件,然后列出

[英]Python loop over files in directory then list

I am trying to loop over files in a directory and list the path of each one. 我试图遍历目录中的文件并列出每个文件的路径。 My code iterates over each file but lists the wrong directory. 我的代码遍历每个文件,但列出了错误的目录。 What am I missing to return the full directory? 返回完整目录时我缺少什么?

Here's my code so far: 到目前为止,这是我的代码:

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)

The structure is like this: 结构是这样的:

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

Output from the terminal (missing the /posts/ part of the directory): 终端的输出(缺少目录的/posts/部分):

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

If you take a look at the source code: 如果您看一下源代码:

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."""

What abspath does is simply join the current working directory with the path you provided, since you only provide the file as a path, and you are one level up of the posts directory it will get ignored. abspath所做的只是将当前工作目录与您提供的path在一起,因为您仅将文件提供为路径,并且您是posts目录的上一级,它将被忽略。

您可以将目录放回路径中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM