Question

Using Python, I want to print all the files inside a given directory, without display the directory itself. I tried to use os.walk but it always print the directory.

for root, dirs, files in os.walk(directory):
        for subFile in files:
            print os.path.join(root, subFile)

I used the directory 'DummyFolder/testFolder'

It prints:

DummyFolder/testFolder/folder1/folder2/file.txt
DummyFolder/testFolder/folder1/folder2/file2.txt
DummyFolder/testFolder/folder3/file3.txt

I want it to print:

folder1/folder2/file.txt
folder1/folder2/file2.txt
folder3/file3.txt

How can it be done?

Thanks!

Was it helpful?

Solution

Use os.path.relpath to get path relative to your directory.

print(os.path.relpath(os.path.join(root, subFile), directory))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top