Skip to content
Search

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

s = os.path.splitext("/My Jukebox/Cool Jazz.mp3")
print s[1]  # .mp3

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.

os.path.exists(path)

To get the absolute path of the currently running script file

os.path.dirname(os.path.abspath( __file__ ))

Get the file name including the extension

os.path.basename(path)

Get the relative path between two paths

os.path.relpath( "c:\\ik" , "c:\\os\\pp" )
# ..\\..\\ik'

Get the common path

os.path.commonprefix( ["c:\\ik\\jj" , "c:\\ik\\sd" ])
# c:\\ik\\'

Remove intermediate path slashes

os.path.normpath( "c:\\os\\..\\pp" )
# c:\\pp'

Get the current working path

os.getcwd()

Join path names

os.path.join( "a" , "b" ,"c" )
# 'a/b/c'

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

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

import os
for p, s, f in os.walk('.'):
    print(p)
    print(s)
    print(f)
    print('------')

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

import os
s = os.environ['PATH']
print s

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

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


  1. SystemSection-Python-os-path.pdf ↩

author Zer0 sitemap