I am searching for a good way to get relative paths of files and (sub)folders within a specific folder.
For my current approach I am using os.walk()
. It is working but it does not seem "pythonic" to me:
myFolder = "myfolder" fileSet = set() # yes, I need a set() for root, dirs, files in os.walk(myFolder): for fileName in files: fileSet.add(root.replace(myFolder, "") + os.sep + fileName)
Any other suggestions?
Thanks
os. listdir() returns everything inside a directory -- including both files and directories. A bit simpler: (_, _, filenames) = walk(mypath). next() (if you are confident that the walk will return at least one value, which it should.)
path. relpath() method in Python is used to get a relative filepath to the given path either from the current working directory or from the given directory. Note: This method only computes the relative path.
Python: Absolute Path vs. Relative Path. An absolute path is a path that describes the location of a file or folder regardless of the current working directory; in fact, it is relative to the root directory. A relative path that depicts the location of a file or folder is relative to the current working directory.
Use os.path.relpath()
. This is exactly its intended use.
import os root_dir = "myfolder" file_set = set() for dir_, _, files in os.walk(root_dir): for file_name in files: rel_dir = os.path.relpath(dir_, root_dir) rel_file = os.path.join(rel_dir, file_name) file_set.add(rel_file)
Note that os.path.relpath()
was added in Python 2.6 and is supported on Windows and Unix.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With