Python-Ref > System interaction > Manipulating files and directories > Path manipulations
 
 

<-^^->
Klíčová slova
Moduly
Knihovní funkce

Path manipulations

Overview of commands for path manipulation.
On the previous pages several commands for path manipulation were shown. The following example makes an overview of them and adds some more.
Expand/Shrink
  1   import os
  2   
  3   paths = ["/home/beda/hello.py", "local.txt", "/sys/bin/", "/sys/bin"]
  4   
  5   for path in paths:
  6       print path
  7       print os.path.abspath( path)  # absolute path
  8       print os.path.split( path)    # split directory prefix and name
  9       print os.path.splitext( path) # split the extension
 10       print os.path.join( path, "example.db")  # join dir + filename
 11       print "------------------------------"
stdout:
/home/beda/hello.py
/home/beda/hello.py
('/home/beda', 'hello.py')
('/home/beda/hello', '.py')
/home/beda/hello.py/example.db
------------------------------
local.txt
/mnt/bkchem.img/projects/python-ref/_tmp/local.txt
('', 'local.txt')
('local', '.txt')
local.txt/example.db
------------------------------
/sys/bin/
/sys/bin
('/sys/bin', '')
('/sys/bin/', '')
/sys/bin/example.db
------------------------------
/sys/bin
/sys/bin
('/sys', 'bin')
('/sys/bin', '')
/sys/bin/example.db
------------------------------
Doba běhu: 21.6 ms
It is important to emphasize that the output shown above was produced on a Linux system, the advantage of using the functions above is that the output on other systems (Windows, Mac OS) will match the rules used on these systems (\ instead of / as a path delimiter on Windows, etc.)
The following code shows a few more fancy functions.
Expand/Shrink
  1   import os
  2   
  3   paths = ["/home/beda/hello.py", "/home/carrot/.emacs", "/home/beda/tmp/example.txt"]
  4   
  5   # find the common prefix of several paths
  6   print os.path.commonprefix( paths)
  7   
  8   # expand the ~ to users home directory
  9   print os.path.expanduser( "~/.emacs")
 10   
 11   # expand environment variables ($XXX)
 12   print os.path.expandvars( "$PWD")
 13   print os.path.join( os.path.expandvars( "$PWD"), ".emacs")
stdout:
/home/
/home/beda/.emacs
/mnt/bkchem.img/projects/python-ref/_tmp
/mnt/bkchem.img/projects/python-ref/_tmp/.emacs
Doba běhu: 22.9 ms