j. doe
j. doe

Reputation: 33

Getting paths to all files in a directory (but not absolute path) in Python 3

I have a directory DATA which contains several subdirectories and inside each subdirectory, there are more directories and files.

Here is my code:

for dirpath,subs,filenames in os.walk("/Users/.../DATA"):
   for f in filenames:
       print(os.path.abspath(os.path.join(dirpath, f)))

The results this code prints out are the absolute directories (ex. "/Users/.../Data/SubFile/SubFile.txt")

The results I want are (ex. "Data/SubFile/Subfile.txt")

Upvotes: 1

Views: 57

Answers (2)

Caleb Mackle
Caleb Mackle

Reputation: 140

What about something simple like this:

dir_path = "/Users/.../DATA"

for dirpath,subs,filenames in os.walk("/Users/.../DATA"):
   for f in filenames:
       print(os.path.abspath(os.path.join(dirpath, f))[len(dir_path):])

Upvotes: 1

jubnzv
jubnzv

Reputation: 1574

Use os.path.commonprefix():

common_prefix = os.path.commonprefix(["/Users/.../DATA"])
for dirpath, subs, filenames in os.walk("/Users/.../DATA"):
    for f in filenames:
        print(os.path.relpath(os.path.join(dirpath, f), common_prefix))

Upvotes: 0

Related Questions