0

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

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

You can just put the directory back into the path:

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

2 Comments

This solves my immediate problem thanks. I'm unsure why the abspath method returns the root of my app.py file instead of the posts directory though
@c4binever: I think you thought abspath would "find a file" but actually it just takes the path you give it and "expands" it relative to the current directory. Since your current directory is . and not ./directory, it didn't do what you wanted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.