The OS module in Python

Source: Internet
Author: User
Tags throw exception python script

The Python OS module provides a unified operating system interface function One, for the operation of the system 1, Os.name is currently using the platform where ' NT ' is windows, ' POSIX ' is a specific path delimiter for Linux or unix2, OS.SEP output operating system. Win under "\", Linux for "/" 3, OS.PATHSEP output divider output for splitting the file path of the string. Under Windows is '; ', Linux under ":" 4, os.linesep newline character output current platform is the line terminator, win under "\ r \ n", Linux under "\ n", Mac use ' \ R '. 5, Os.environ get the system environment variable PATH6, Os.system (' dir c:\\ ') execute the system command directly assume there is a shell script test.sh:
[Email protected]:~$ VI test.sh
[Email protected]:~$ more test.sh
#!/bin/bash
echo ' Hello python! '
echo ' Hello world! '
Exit 1 >>> Import OS
>>> Os.system ("./test.sh")
Hello python!
Hello world!
256 7, Os.popen () executes a system command that saves the execution result to a file handle (similar to the Open function in Python) dirlist=os.popen (' dir d:\\tmp ') for I in Dirlist:print i > > Import OS
>>> Os.popen ("./test.sh")
<open file './test.sh ', mode ' R ' at 0x7f6cbbbee4b0>
>>> F=os.popen ("./test.sh")
>>> F
<open file './test.sh ', mode ' R ' at 0x7f6cbbbee540>
>>> F.readlines ()
[' Hello python!\n ', ' Hello world!\n ']  II, for directory operation 1, OS.GETCWD () Gets the current working directory, which is the directory path of the current Python script work. Results: E:\python\05072, Os.chdir (' d:\\ ') modifies the current working directory 3, OS.CURDIR returns the current directory 4, os.pardir directory switch to parent directory (top level directory)   Third, action on file 1, Os.listdir (' e:\\tmp ') lists all files and subdirectories in the specified directory, including hidden files or directories, and returns them as a list. 2, Os.rename (' e:\\tmp\\1.txt ', ' e:\\tmp\\1new.txt ') modify the file name 3, Os.stat (' e:\\tmp\\02.txt ') to get the life cycle of the Files 4, Os.utime ( path[, (Atime, Mtime)]) modifies the file's Time property settings file's access and modified time for a given time if the Atime and Mtime parameters are not specified, the modification will be the current time. 5. Os.access () The output file has Write permission: Print os.access (Filename,os. W_OK) Print os.access (Fn,os. R_OK) file has Read permissions for print os.access (Fn,os. X_OK) file has permission to execute   Four, os.path1, os.path.exists (path) returns the current directory or whether the file exists to determine if the path exists, or False if there is a return of true. 2, Os.path.isabs (path) determines whether the path is an absolute path, and if true, returns False if it is the absolute path. 3, Os.path.isfile (path) determines whether the file determines whether the path is a file, or False if it returns true. 4, Os.path.isdir (path) determines whether the directory determines whether the path is a directory, or False if the directory returns TRUE. 5, Os.path.getsize (PATH): Units are bytes to return the size of the file or directory. Gets the file size, if name is the directory that returns 0L, and if the name represents a directory or file that does not exist, the windowserror exception is reported. 6, Os.path.abspath (path) Gets the absolute path (butThis path is not necessarily a real path) eg:print Os.path.abspath (' d:\\tmp\\test13.txt ') print Os.path.abspath (' Test13.txt ') # Returns the path to the file name under the current execution directory, and returns the print OS.GETCWD () result when the file is not present: d:\tmp\test13.txtd:\python\0512\test13.txtd:\python\05127, Os.path.normpath (path) converts path to the standard path. Used to solve cross-platform problems  , get the drive letter from the path, file name, extension, directory 1, Os.path.split (path) to the file path to do the partition, the last \ \ After the file directory to split the path into a directory and file name (in fact, If you use the directory completely, it will also separate the last directory as the file name, and it will not determine whether the file or directory exists, and it is returned in the tuple. Eg:print os.path.split (' d:\\tt4\\c12 ') print os.path.split (' d:\\tt4\\c12\\ ') print os.path.split (' d:\\tt4\\c12\\ T1.txt ') Results: (' d:\\tt4 ', ' C12 ') (' d:\\tt4\\c12 ', ') ' (' D:\\tt4\\c12 ', ' T1.txt ') 2, Os.path.dirname (path)   The name of the returned directory returns the path's directory, which is actually the first element of Os.path.split (path). 3. Os.path.basename (path) returns the name of the file that returns the last file name of the path. If path ends with a/or \, a null value is returned. The second element of Os.path.split (path). 4. Os.path.splitext (path) cut the paths and extensions separately print os.path.splitext (' 01.py ') print os.path.splitext (' d:\\tmp\\001.txt ') print Os.path.splitext (' d:\\tt4\\c12 ') Result: (' "", '. Py ') (' d:\\tmp\\001 ', '. txt ') (' d:\\tt4\\c12 ', ') ' Filename,expandname = Os.path.splitext (fThe path and extension can be assigned directly to two variables, in fact, a tuple 5, os.path.splitdrive (path) split drive (letter) and the following path. Splits the drive and file paths and returns the results in tuples, primarily for win, and the first of the Linux tuples is always empty. The return result is Ganso 6, Os.path.join (path,*paths) combines all the paths into absolute paths. Connect two or more path names, separated by "\", if the given parameters are absolute path names, the first given absolute path will be discarded   six, Os.walk ()The Os.walk () method is used to go through the directory tree to output the file name in the directory, up or down.

Valid in Unix,windows.

Grammar

The syntax format for the Walk () method is as follows:

Os.  Walk(top[, topdown=True[, onerror=None[, followlinks =False]])                
Parameters
    • Top -Every folder in the root directory (including itself), resulting in 3-tuple (Dirpath, dirnames, filenames) "Folder path, folder name, file name".

    • Topdown --optional, true or unspecified, a 3-tuple of a directory will be generated first (directory top-down) than the 3-tuple of any of its subfolders. If Topdown is False, a 3-tuple of a directory will be generated after the 3-tuple of any of its subfolders (directory bottom-up).

    • onerror --optional, is a function; It is called when there is a parameter, an OSError instance. After reporting this error, continue to walk, or throw exception to terminate walk.

    • followlinks --set to True to access the directory through a soft link.

The following example demonstrates the use of the Walk () method:

#!/usr/bin/python#-*-Coding:utf-8-*-ImportOsForRoot,Dirs,FilesInchOs.Walk(".",Topdown=False): For name in Files: print (os. Path. Joinroot, Name for name in Dirs: print (os path.root, Name  

Execute the above program output as:

./.Bash_logout./Amrood.Tar.Gz./.emacs./httpd. Conf./www.. Gz./mysql.. Gz./test../. Bashrc./. Bash_history./. Bash_profile./tmp./tmp /test.                 

OS modules in Python

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.