Reputation: 33
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
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
Reputation: 1574
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