Python OS module introduction, pythonos Module

Source: Internet
Author: User

Python OS module introduction, pythonos Module

OS. getcwd () obtains the current working directory, that is, the directory path of the current python script.
OS. chdir ("dirname") changes the current script working directory, which is equivalent to the cd
OS. curdir :('.')
OS. pardir :('..')
OS. makedirs ('dirname1/dirname2 ') can generate multi-layer recursive directories.
OS. removedirs ('dirname1') if the directory is empty, delete it and recursively go to the upper-level directory. If the directory is empty, delete it.
OS. mkdir ('dirname') to generate a single-level Directory, which is equivalent to mkdir dirname in shell.
OS. rmdir ('dirname') deletes a single-stage empty directory. If the directory is not empty, it cannot be deleted and an error is returned. This is equivalent to rmdir dirname in shell.
OS. listdir ('dirname') lists all files and subdirectories in a specified directory, including hidden files, and prints them in list mode.
OS. remove () delete an object
OS. rename ("oldname", "newname") rename a file/directory
OS. stat ('path/filename ') to get the file/directory information
OS. symlink ('path/filename', 'ln _ filename') creates a symbolic link. The source must be 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 the Python interaction mode and go to >>> 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

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

  • Top indicates the path of the directory tree to be traversed
  • The default value of topdown is "True", indicating that the files under the directory tree are first returned, and then the subdirectories in the directory tree are traversed. if the value of Topdown is "False", the system first traverses the subdirectories of the directory tree, returns the files under the subdirectories, and finally returns the files under the root directory.
  • The default value of onerror is "None", indicating to ignore Errors generated by file time. If it is not empty, a user-defined function will be provided to indicate an error message and continue traversal or throw an exception to stop traversal.

This function returns a tuple with three elements representing the path name, directory list, and file list for each traversal.
Example of OS. walk:

>>> 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 file path... for name in dirs :... print (OS. path. join (root, name) # print the absolute directory path...
OS. tmpfile () Create and open a new temporary file 'W + B'
OS. sep: Specifies the path delimiter of the output operating system. The path in win is \, and the path in Linux is "/"
OS. linesep: output the line terminator used by the current platform. The line terminator is \ t \ n in win, and the line terminator is \ n in Linux"
OS. pathsep output the string used to split the file path
OS. name output string indicates the current platform. Win-> 'nt '; Linux-> 'posix'
OS. system ("bash command") run the shell command to directly display
OS. popen ("bash command") runs the shell command to generate an object that can be assigned to a variable, and then read it with read >>> import OS >>> OS. system ('ls Twisted') chat_client_twisted.py chat_server_twisted.py0 >>> ls = OS. popen ('ls Twisted') >>> ls. readlines () ['chat _ client_twisted.py \ n', 'chat _ server_twisted.py \ n']
OS. environ: Get system environment variables
OS. access ('pathfile', OS. W_ OK) checks the File Permission mode and outputs True and False.
OS. chmod ('pathfile', OS. W_ OK) changes 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

Common modules of OS. path

OS. path. abspath (path) returns the absolute path of path normalization >>> 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) splits the path into two groups of directories and file names and returns >>> OS. path. split ('/root/py/c. py') ('/root/py', 'C. py ') >>> OS. path. split ('/root/py/') ('/root/py ','')
OS. path. dirname (path) returns the path directory. It is actually the OS. path. the first element of split (path) >>> OS. path. dirname ('/root/py/c. py') '/root/py'> OS. path. dirname ('C. py ')''
OS. path. basename (path) returns the final file name of the path. If the path ends with a slash (/) or slash (\), a null value is returned. That is, OS. path. the second element of split (path) >>> OS. path. basename ('/root/py/c. py') 'C. py '> OS. path. basename ('/root/py') 'py'
OS. path. commonprefix (list) returns the longest paths of all paths in the list, from left to right, with the same characters.
OS. path. exists (path) If path exists, True is returned. If path does not exist, False is returned.
OS. path. isabs (path) returns True if path is an absolute path.
OS. path. isfile (path) If path is an existing file, True is returned. Otherwise, False is returned.
OS. path. isdir (path) If path is an existing Directory, True is returned. Otherwise, False is returned.
OS. path. join (path1 [, path2 [,...]) returns the results after combining multiple paths. The parameters before the first absolute path are ignored.
OS. path. normcase (path) in Linux, the function returns the path as is, and all characters in the path are converted to lowercase letters on windows platform, and convert all slashes into backslash >>> OS. path. normcase ('C:/windows \ system32 \ ') 'C: \ windows \ system32 \\'
OS. path. normpath (path) canonicalized path> OS. path. normpath ('C: // windows \ System32 \\.. /Temp/') 'C: \ windows \ Temp'
OS. path. splitdrive (path) splits the drive name and path, mainly for win, and for linux tuples, the first is always empty >>> OS. path. splitdrive ('C: \ Windows') ('C: ',' \ Windows ')
OS. path. splitext (path) separates the file name and extension. The (fname, fextension) tuples are returned by default for partitioning. "Is the separator >>> OS. path. splitext ('/root/py/c. py ') ('/root/py/C ','. py ')
OS. path. getsize (path) returns the size (in bytes) of the path)
OS. path. getatime (path) returns the last access time of the file or directory pointed to by path.
OS. path. getmtime (path) returns the last modification time of the file or directory pointed to by path.

OS. path. walk (top, func, arg)

  • Top indicates the path of the directory tree to be traversed
  • Func indicates the callback function to process the traversal path. a callback function is used as a parameter of a function. When triggered at a time, the program calls a defined callback function to process a task. the callback function must provide three parameters: the 1st parameter is the parameter tag of the walk () parameter, the 2nd parameter represents the directory list, and the 3rd parameter represents the file list.
  • Arg is the tuple passed to the callback parameter func. One Parameter of the callback function must be arg, which provides processing parameters for the callback function. The parameter arg can be blank.
>>> 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

The file name list generated by OS. path. walk () and OS. walk () is different. OS. path. walk () generates the directory path and file path under the directory tree, while OS. walk () only generates the file path

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.