whatevermike
whatevermike

Reputation: 196

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):

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

Upvotes: 0

Views: 2473

Answers (2)

akuiper
akuiper

Reputation: 215137

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.

Upvotes: 3

John Zwinck
John Zwinck

Reputation: 249642

You can just put the directory back into the path:

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

Upvotes: 1

Related Questions