How to do it...

  1. Print all the filenames in the dir directory and subdirectories:
>>> import os
>>> for root, dirs, files in os.walk('.'):
... for file in files:
... print(file)
...
file1.txt
file2.txt
file6.pdf
file3.txt
file4.txt
file5.pdf
  1. Print the full path of the files, joining with the root:
>>> for root, dirs, files in os.walk('.'):
... for file in files:
... full_file_path = os.path.join(root, file)
... print(full_file_path)
...
./dir/file1.txt
./dir/file2.txt
./dir/file6.pdf
./dir/subdir/file3.txt
./dir/subdir/file4.txt
./dir/subdir/file5.pdf
  1. Print only the .pdf files:
>>> for root, dirs, files in os.walk('.'):
... for file in files:
... if file.endswith('.pdf'):
... full_file_path = os.path.join(root, file)
... print(full_file_path)
...
./dir/file6.pdf
./dir/subdir/file5.pdf
  1. Print only files that contain an even number:
>>> import re
>>> for root, dirs, files in os.walk('.'):
... for file in files:
... if re.search(r'[13579]', file):
... full_file_path = os.path.join(root, file)
... print(full_file_path)
...
./dir/file1.txt
./dir/subdir/file3.txt
./dir/subdir/file5.pdf
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.56.158