Python:os
lastmod 2022-02-23created 2015-03-0511 edits
path
In python, the module for path handling is os.path.
Directory/file name/extension
Use the following functions to get the directory/file name/extension.
-
split -
splitdrive -
splitext
Extension name
Drive name
# 드라이브명까지 포함된 Windows 전용 패스를 취급
s = os.path.splitdrive("D:/My Jukebox/Cool Jazz.mp3")
print s[0] # D:
Example
Returns True if the given path exists, and False if it does not. On OSes like Linux, it may also return False when the file or directory exists but there is no read permission.
To get the absolute path of the currently running script file
Get the file name including the extension
Get the relative path between two paths
Get the common path
Remove intermediate path slashes
Get the current working path
Join path names
walk
Generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames).
Find files recursively
- Stackoverflow: Use a Glob() to find files recursively in Python?
- Jump to Python: Searching subdirectories
- python/os.walk filtering os_walkf
Use os.walk to recursively walk a directory and fnmatch.filter to match against a simple expression:
import fnmatch
import os
matches = []
for root, dirnames, filenames in os.walk('src'):
for filename in fnmatch.filter(filenames, '*.c'):
matches.append(os.path.join(root, filename))
Example
The output is as follows:
.
['src', 'etc', 'var', 'bin', 'tparty', '.git']
['LICENSE', '.gitignore', 'install.sh', 'INFORMATION', '.gitattributes', 'profile.sh', 'README.md']
------
./src
['opwm']
[]
------
./src/opwm
[]
['dwm.h', '.gitignore', 'util.c', 'install.sh', 'draw.h', 'dwm.c', 'draw.c', 'util.h', 'CMakeLists.txt', 'wmname.c']
------
./etc
['nodejs', 'gdb', 'dependencies', 'tmux', 'coturn', 'conky', 'qtile', 'picom', 'hyper', 'profile.d', 'git', 'xmobar', 'alacritty', 'docker', 'xmonad', 'clang-format', 'n', 'font', 'swarm', 'crawling', 'cuda', 'lldb', 'ffmpeg', 'rust', 'vim', 'eclipse', 'i3', 'x11', 'install.d']
[]
------
...
Get-Print Environment Variable
Troubleshooting
FileNotFoundError in os.getcwd
os.getcwd() can raise FileNotFoundError. This happens when the working directory has been removed for some reason (e.g. by another process, etc ...). os.getcwd() seems to look up the current directory.
In short, check whether another process is removing the directory.
See also
- Python
- Python:os
- Python:grp - Group DB
- Python:pwd - Password DB
- Python:re - Regular expressions.
File and directory access
- Python:pathlib - Object-oriented file system paths
- Python:os.path - Common pathname manipulations
- Python:fileinput - Iterate over lines from multiple input streams
- Python:stat - Interpreting stat() results
- Python:filecmp - File and directory comparisons
- Python:tempfile - Generate temporary files and directories
- Python:glob - Unix style pathname pattern expansion
- Python:fnmatch - Unix filename pattern matching
- Python:linecache - Random access to text lines
- Python:shutil - High-level file operations
Favorite site
References
-
SystemSection-Python-os-path.pdf ↩