The OS. path module mainly integrates the path folder operation function. here we will take a look at the operation method summary in the OS. path module in Python. For more information, see
Resolution path
Path parsing dependency and some variables defined in OS:
- OS. sep-delimiter between all parts of the path.
- OS. extsep-delimiter between file names and file extensions.
- OS. pardir-indicates the upper-level part of the directory tree.
- OS. curdir-the part of the current directory in the path.
The split () function splits the path into two separate parts and returns the tuple containing the results. The second element is the last part of the path, and the first element is the other part.
import os.pathfor path in [ '/one/two/three', '/one/two/three/', '/', '.', '']: print '%15s : %s' % (path, os.path.split(path))
When the input parameter ends with OS. sep, the last element is an empty string.
Output:
/one/two/three : ('/one/two', 'three')/one/two/three/ : ('/one/two/three', '') / : ('/', '') . : ('', '.') : ('', '')
The value returned by the basename () function is equivalent to the second part of the split () value.
import os.pathfor path in [ '/one/two/three', '/one/two/three/', '/', '.', '']: print '%15s : %s' % (path, os.path.basename(path))
The entire path is stripped to only the last element.
Output:
/one/two/three : three/one/two/three/ : / : . : . :
The dirname () function returns the first part of the decomposition path.
import os.pathfor path in [ '/one/two/three', '/one/two/three/', '/', '.', '']: print '%15s : %s' % (path, os.path.dirname(path))
Combine basename () with dirname () to obtain the original path.
/one/two/three : /one/two/one/two/three/ : /one/two/three / : / . : :
Splitext () is similar to split (), but it breaks down the path based on the extension separator rather than the directory separator. Import OS. path
for path in [ '/one.txt', '/one/two/three.txt', '/', '.', '' 'two.tar.gz']: print '%21s : %s' % (path, os.path.splitext(path))
Only the last appearance of OS. extsep is used to find the extension.
/one.txt : ('/one', '.txt') /one/two/three.txt : ('/one/two/three', '.txt') / : ('/', '') . : ('.', '') two.tar.gz : ('two.tar', '.gz')
Commonprefix () takes a path list as the parameter and returns a string, indicating the public prefix in all paths.
import os.pathpaths = [ '/one/two/three', '/one/two/threetxt', '/one/two/three/four',]for path in paths: print 'PATH:', pathprintprint 'PREFIX:', os.path.commonprefix(paths)
Output:
PATH: /one/two/threePATH: /one/two/threetxtPATH: /one/two/three/fourPREFIX: /one/two/three
Create Path
In addition to splitting existing paths, you also need to create paths from other strings and use join ().
import os.pathfor parts in [ ('one', 'two', 'three'), ('\one', 'two', 'three'), ('/one', '/two', '/three', '/four'),]: print parts, ':', os.path.join(*parts)
If a parameter to be connected starts with OS. sep, all the preceding parameters will be discarded and the start part of the parameter will be returned.
('one', 'two', 'three') : one\two\three('\\one', 'two', 'three') : \one\two\three('/one', '/two', '/three', '/four') : /four
Canonicalized path
When you use join () or use embedded variables to combine paths from individual strings, the resulting paths may end with redundant delimiters or relative paths. you can use normpath () to clear these contents.
import os.pathfor path in [ 'one/two/three', 'one/./two/three', 'one/../alt/two/three', ]: print '%20s : %s' % (path, os.path.normpath(path))
You can compute and compress the path segments composed of OS. curdir and OS. pardir.
one/two/three : one\two\three one/./two/three : one\two\threeone/../alt/two/three : alt\two\three
To convert a relative path to an absolute file name, you can use abspath ().
import os.pathfor path in [ '.', '..', 'one/two/three', 'one/./two/three', 'one/../alt/two/three', ]: print '%20s : %s' % (path, os.path.abspath(path))
The result is the complete path starting from the top-level of a file system tree.
. : C:\Users\Administrator\Desktop .. : C:\Users\Administrator one/two/three : C:\Users\Administrator\Desktop\one\two\three one/./two/three : C:\Users\Administrator\Desktop\one\two\threeone/../alt/two/three : C:\Users\Administrator\Desktop\alt\two\three
File time
import osimport timeprint 'File:', __file__print 'Access time:', time.ctime(os.path.getatime(__file__))print 'Modified time:', time.ctime(os.path.getmtime(__file__))print 'Change time:', time.ctime(os.path.getctime(__time__))print 'Size:', os.path.getsize(__file__)
Return the access time, modification time, creation time, and data volume in the file.
Test File
When a program encounters a path name, it usually needs to know some information about the path.
import os.pathfilename = r'C:\Users\Administrator\Desktop\tmp'print 'File :', filenameprint 'Is file? :', os.path.isfile(filename)print 'Absoulute :', os.path.isabs(filename)print 'Is dir? :', os.path.isdir(filename)print 'Is link? :', os.path.islink(filename)print 'Mountpoint? :', os.path.ismount(filename)print 'Exists? :', os.path.exists(filename)print 'Link Exists? :', os.path.lexists(filename)
Boolean values are returned for all tests.
File : C:\Users\Administrator\Desktop\tmpIs file? : FalseAbsoulute : TrueIs dir? : TrueIs link? : FalseMountpoint? : FalseExists? : TrueLink Exists? : True
Traverse a directory tree
import osimport os.pathimport pprintdef visit(arg, dirname, names): print dirname, arg for name in names: subname = os.path.join(dirname, name) if os.path.isdir(subname): print '%s/' % name else: print ' %s' % name printif not os.path.exists('example'): os.mkdir('example')if not os.path.exists('example/one'): os.mkdir('example/one')with open('example/one/file.txt', 'wt') as f: f.write('i love you')with open('example/one/another.txt', 'wt') as f: f.write('i love you, two')os.path.walk('example', visit, '(User data)')
A Recursive directory list is generated.
example (User data)one/example\one (User data) another.txt file.txt
Some practical usage collections:
# Create a File: OS. mknod ("test.txt") creates an empty file fp = open ("test.txt", w) to open a file directly. if the file does not exist, create a file # obtain the extension >>> OS. path. splitext ('/Volumes/Leopard/Users/Caroline/Desktop/1.mp4') [1: kernel ('.mp4 ',) >>> OS. path. splitext ('/Volumes/Leopard/Users/Caroline/Desktop/1.mp4'{1}'.mp4' # get the file name >>> print OS. path. basename (r'/root/hahaha/123.txt'%123.txt> print OS. path. dirname (r'/root/hahaha/123.txt ')/root/hahaha # determine the existence of a directory or File: >>> OS. path. exists ('/root/1. py ') True> OS. path. exists ('/root/') True >>> OS. path. exists ('/root') True >>> OS. path. isdir ('/root') True # Change the working directory: >>> OS. chdir ('/home') >>> OS. getcwd () '/home' # string Segmentation: >>>'/usr/bin/env '. split ('/') ['', 'usr', 'bin', 'env'] # get the folder size (Python2.x): import OS from OS. path import join, getsize def getdirsize (dir): size = 0L for root, dirs, files in OS. walk (dir): size + = sum ([getsize (join (root, name) for name in files]) return size if _ name _ = '_ main _': filesize = getdirsize ('/tmp') print 'There are %. 3f' % (filesize/1024/1024), 'mbytes in/tmp '# get the folder size (Python3.x): import OS from OS. path import join, getsize def getdirsize (dir): size = 0 for root, dirs, files in OS. walk (dir): size + = sum ([getsize (join (root, name) for name in files]) return size if _ name _ = '_ main _': filesize = getdirsize ('/tmp') print ('There are '+ str (filesize/1024/1024) + 'mbytes in/tmp ')