Johnny Metz
Johnny Metz

Reputation: 5965

python os: get all absolute file paths under a certain directory

I have the following folder structure:

Desktop
├── dir1
│   ├── dir2
│   │   └── file4.pdf
│   ├── file2.pdf
│   └── file3.pdf
└── file1.pdf

I'm trying to return all of the files with their paths relative to the current working directory (Desktop). Based on my example above, I want:

Desktop/file1.pdf
Desktop/dir1/file2.pdf
Desktop/dir1/file3.pdf
Desktop/dir1/dir2/file4.pdf

This is what I have so far but it's not recognizing the nested directories:

import os
for dirpath, dirnames, filenames in os.walk('/Users/Me/Desktop'):
    for file in filenames:
        print os.path.abspath(file)

# /Users/Me/Desktop/file1.pdf
# /Users/Me/Desktop/file2.pdf
# /Users/Me/Desktop/file3.pdf
# /Users/Me/Desktop/file4.pdf

Upvotes: 0

Views: 5454

Answers (1)

gandaliter
gandaliter

Reputation: 10101

filenames is just a list of the names of the files, and doesn't store any directory information. That comes from dirpath, which you're ignoring at the moment.

import os
for dirpath, dirnames, filenames in os.walk('/Users/Me/Desktop'):
    for file in filenames:
        print os.path.join(os.path.relpath(dirpath, '/Users/Me/Desktop'), file)

Edit: added os.path.relpath to give relative rather than absolute paths. See this answer.

Upvotes: 3

Related Questions