Introduction to the Python OS module

  • 2020-04-02 14:27:47
  • OfStack

os.getcwd()  Gets the current working directory, current python Directory path for script work  

os.chdir("dirname")  Change the current script working directory; The equivalent of shell Under the cd

os.curdir  Return to current directory : ('.')

os.pardir  Gets the string name of the current directory's parent directory: ('..')

os.makedirs('dirname1/dirname2')  Multiple levels of recursive directories can be generated 

os.removedirs('dirname1')  If the directory is empty, delete, and recurse to the next directory, if it is also empty, delete, and so on 

os.mkdir('dirname')  Generate single level directory; The equivalent of shell In the mkdir dirname

os.rmdir('dirname')  Delete single-level empty directory, if the directory is not empty can not be deleted, error; The equivalent of shell In the rmdir dirname

os.listdir('dirname')  Lists all files and subdirectories in the specified directory, including hidden files, and prints them as a list 

os.remove()  Delete a file 

os.rename("oldname","newname")  Rename file / directory 

os.stat('path/filename')  Access to the file / The directory information 

os.symlink('path/filename','ln_filename')  To create a symbolic link, the source needs an absolute path 

os.utime()  Modify the time attribute 
>>> import os
>>> stinfo = os.stat('c.py')
>>> print "access time of c.py: %s nmodified time of c.py: %s" % (stinfo.st_atime,stinfo.st_mtime)
access time of c.py: 1375448908.0
modified time of c.py: 1369735909.0
>>> os.utime('c.py',(1375448978,1369735977))
>>> print "access time of c.py: %s nmodified time of c.py: %s" % (stinfo.st_atime,stinfo.st_mtime)
access time of c.py: 1375448908.0
modified time of c.py: 1369735909.0
 exit Python Interactive mode, enter again 
>>> import os
>>> stinfo = os.stat('c.py')
>>> print "access time of c.py: %s nmodified time of c.py: %s" % (stinfo.st_atime,stinfo.st_mtime)
access time of c.py: 1375448978.0
modified time of c.py: 1369735977.0

os.walk()  Generates all file names under a directory tree 

(top [OS. Walk, topdown = True [, onerror = None [, followlinks = False]]])

Top represents the path to the directory tree that needs to be traversed The default value of topdown is "True", which means that the file under the directory tree is returned first, and then the subdirectory of the directory tree is traversed The default value of onerror is "None", which indicates that the file traversal is ignored. If it is not empty, a custom function is provided to continue the traversal after the error message or to throw an exception to abort the traversal

This function returns a tuple with three elements representing the path name, directory list, and file list for each iteration
OS. Walk () example:


>>> import os
>>> for root, dirs, files in os.walk("wd/chat", topdown=False):
... for name in files:
...  print(os.path.join(root, name)) # Print the absolute path to the file 
... for name in dirs:
...  print(os.path.join(root, name)) # Print the absolute path to the directory 
...

os.tmpfile()  Create and open ' w+b' A new temporary file 

os.sep  Output the OS specific path separator, win for "\",Linux for "/"

os.linesep  Output the line terminator used by the current platform, win for "tn",Linux for "n"

os.pathsep  Output the string used to split the file path 

os.name  The output string indicates the currently used platform. win->'nt'; Linux->'posix'

os.system("bash command")  run shell Command, display directly 

os.popen("bash command")  run shell Command, generate an object, assign a variable, and use it again read read 
>>> import os
>>> os.system('ls twisted')
chat_client_twisted.py chat_server_twisted.py
0
 
>>> LS = os.popen('ls twisted')
>>> LS.readlines()
['chat_client_twisted.pyn', 'chat_server_twisted.pyn']

os.environ  Gets system environment variables 

os.access('pathfile',os.W_OK)  Verify file permission mode, output True . False

os.chmod('pathfile',os.W_OK)  Change the file permission mode 

# echo 'test' > test.sh
>>> os.access('test.sh',os.W_OK)
True
>>> os.access('test.sh',os.X_OK)
False
>>> os.chmod('test.sh',os.X_OK)
>>> os.access('test.sh',os.X_OK)
True
# ls -l test.sh
---------x 1 root root 12 Oct 20 23:03 test.sh

Os.path is often detailed in modules


os.path.abspath(path)  return path The normalized absolute path 
>>> import os.path
>>> os.path.abspath('c.py')
'/root/py/c.py'
>>> os.path.abspath('../py/c.py')
'/root/py/c.py'

os.path.split(path)  will path Returns split into a binary group of directories and file names 
>>> os.path.split('/root/py/c.py')
('/root/py', 'c.py')
>>> os.path.split('/root/py/')
('/root/py', '')

os.path.dirname(path)  return path The directory. In fact, is os.path.split(path) The first element of 
>>> os.path.dirname('/root/py/c.py')
'/root/py'
>>> os.path.dirname('c.py')
''

os.path.basename(path)  return path Last file name. How to path Ends with/or, then a null value is returned. namely os.path.split(path) The second element 
>>> os.path.basename('/root/py/c.py')
'c.py'
>>> os.path.basename('/root/py')
'py'

os.path.commonprefix(list)  return list In which all path Longest path in common, from left to right, same character 

os.path.exists(path)  if path Exist, return True ; if path Does not exist. Returns False

os.path.isabs(path)  if path Absolute path, return True

os.path.isfile(path)  if path Is an existing file, returns True . Otherwise returns False

os.path.isdir(path)  if path Is an existing directory, then returns True . Otherwise returns False

os.path.join(path1[, path2[, ...]])  When multiple paths are combined and returned, arguments before the first absolute path are ignored 

os.path.normcase(path)  in Linux Below, the function returns as is path In the windows The platform converts all characters in the path to lowercase and all slashes to backslashes 
>>> os.path.normcase('c:/windows\system32\')
'c:\windows\system32\'

os.path.normpath(path)  Normalized path 
>>> os.path.normpath('c://windows\System32\../Temp/')
'c:\windows\Temp'

os.path.splitdrive(path)  Split drive name and path, main pair win for linux The first tuple is always empty 
>>> os.path.splitdrive('c:\windows')
('c:', '\windows')

os.path.splitext(path)  Separate file name and extension; The default return (fname,fextension) Tuple, can do the shard operation   In order to" . "Is the separator 
>>> os.path.splitext('/root/py/c.py')
('/root/py/c', '.py')

os.path.getsize(path)  return path Size (bytes) 

os.path.getatime(path)  return path The last access time of the file or directory to which you are referring 

os.path.getmtime(path)  return path The last time a file or directory was modified 

OS. Path. Walk (top, func, arg)

Top represents the path to the directory tree that needs to be traversed Callback function func, to deal with traversal path. The so-called callback function, is used as a function's parameters, when some time trigger, the program will call the callback function is defined to handle a task. The callback function must provide three parameters: the first parameter to walk () the parameters of the tag, the second parameter directory list, a third parameter file list Arg is a tuple passed to the callback parameter func. One argument to the callback function must be an arg to provide a processing parameter to the callback function. The parameter arg can be null

>>> import os
>>> def VisitDir(arg,dirname,names):
... for filespath in names:
...  print os.path.join(dirname,filespath)
...
>>> path='/root/py/wd/chat'
>>> os.path.walk(path,VisitDir,())
/root/py/wd/chat/chat_server.py
/root/py/wd/chat/chat_client.py
/root/py/wd/chat/test
/root/py/wd/chat/test/linuxeye
/root/py/wd/chat/test/test2
/root/py/wd/chat/test/test3
/root/py/wd/chat/test/test2/asdf
/root/py/wd/chat/test/test3/sdfaxx

Os.path. Walk () does not produce the same list of file names as os.walk(). Os.path. Walk () produces the directory path and the file path under the directory tree, while os.walk() produces only the file path


Related articles: