Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Get relative path of all files and subfolders in a directory

Tags:

python

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

like image 409
vobject Avatar asked Jul 28 '09 09:07

vobject


People also ask

How do you get the paths of all files in a folder in Python?

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.)

How do I find the relative path of a file in Python?

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.

How do you use absolute path instead of relative path in Python?

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.


1 Answers

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.

like image 184
Newtonx Avatar answered Sep 20 '22 09:09

Newtonx