Third, file system operation
The functionality of the OS module consists primarily of the file System section and the process section, which describes the file system-related sections.
When the request operating system fails, the OS module returns the built-in exception exceptions. OSError instance, you can access this type through Os.error, oserror instance has three kinds of attributes:
- errno: Error code for operating system error
- Strerror: A string describing the error;
- FileName: The file on which the operation was faulted.
Useful properties provided by the OS module
>>> Os.curdir
‘.‘
A string representing the current directory, which is "." On both UNIX and Windows.
>>> os.pardir ' ... '
A string representing the parent directory, both UNIX and Windows are ".."
>>> Os.defpath '.; C:\\bin '
The default search path for the program, which is used if the PATH environment variable is missing.
>>> os.linesep ' \ r \ n '
The end string of the text line, on Unix, ' \ n ', on Windows ' \ r \ n '.
>>> os.linesep ' \ r \ n '
Separators for separating file extensions and filenames are "." On Unix and Windows.
>>> os.pathsep '; '
The delimiter used to separate paths in the path list can refer to the PATH environment variable, which is ":" On the UNIX platform and ";" on the Windows platform.
>>> os.sep ' \ \ '
The path consists of a "/" on the UNIX platform and "\ \" on the Windows platform.
File system-related methods provided by the OS module
Os.access (path, mode) # e.g. >>> os.access ("C:\Windows\System32", OS. R_OK | Os. W_OK) True
The access () function determines whether the real user (group) of the current process (real user/real Group) has permission to perform all of the operations listed in mode on path paths, and the optional values for the parameter mode are:
- Os. F_OK: Whether the file specified by the path exists;
- Os. R_OK: Whether the file specified by the path is readable;
- Os. W_OK: Whether the file specified by the path is writable;
- Os. X_OK: Whether the file specified by the path is executable;
Os.chdir (PATH)
# e.g.
>>> Os.chdir ("c:/")
equals the CD to path, which will switch the PWD to the path specified by path.
Os.chmod (path, mode)
Set the access permission for path to mode, which can be 0 or more OS. R_ok,os. W_ok,os. X_OK, also a 3-bit 8-binary integer (Unix platform), such as 0777, 0664, etc.
OS.GETCWD () #e .g.>>> os.getcwd () ' c:\\ '
GETCWD () Gets the path to the current working directory.
Os.listdir (PATH)
Listdir (path) Returns a list that includes all the files and directories under path paths, but does not include "." and ".." Directory.
The list returned by Listdir () is unsorted.
Os.mkdirs (Path, mode=0777) os.mkdir (path, mode=0777)
Create a directory where path may involve a multi-level directory, Mkdirs will create all directories that do not already exist along the path, and then set access permissions, while mkdir () creates only the base address at the far right of the route, if there is a directory that has not yet been created, mkdir () Throws an exception OSError.
Both functions throw oserror when the creation fails, and the same exception is thrown when the specified path already exists.
Os.remove (path) os.unlink (path)
These two functions delete the file specified by path.
Os.removedirs (PATH)
Remove all directories that pass through the path (the directory that is required to be empty).
Os.rmdir (PATH)
Deletes the directory specified by path (requires a directory to be empty), throws OSError when the deletion fails, for example, the deleted directory is not empty.
Os.rename (SRC, dest)
Rename the file or directory src to dest.
Os.renames (SRC, dest)
Renamed, but the process of renaming will automatically create an intermediate path in the parameter dest that does not already exist, and will delete the empty directories contained in SRC after renaming.
Os.stat (PATH)
Returns a value of type Stat_result that provides 10 information about the path of the parameter, which can be accessed through the corresponding property, for example:
1 >>> os.path.getsize (' test1.py '0l3 >>> os.stat (' test1.py '). St_size4 0L
The 10 types of information about files, directories, and their corresponding property names are:
Property name |
Meaning |
St_mode |
Access control and other mode bits |
St_ino |
The ordinal of the I node |
St_dev |
Device number |
St_nlink |
Number of hard links |
St_uid |
The UID of the owner |
St_gid |
The owner of the GID |
St_size |
Size (units: bytes) |
St_atime |
Last access time (number of seconds since epoch) |
St_mtime |
Last Modified Time |
St_ctime |
Time of last state change |
Os.utime (Path, Times=none)
Set the last access and last modified time of the file,
- If the Times is none, then Utime () uses the current time;
- If the Times is not none, the time must be a two-tuple-(accessed, modified), which specifies the last access and modification, where both values are the number of seconds since the epoch.
Os.walk (Top, topdown=true, Onerror=none)
First, this function is a generator! Used to traverse the directory specified by the parameter top
- When the parameter topdown is true (the default), traverse from top to its subdirectory
- When the parameter Topdown is false, the reverse step is started from the leaf node of the top tree, and the inverse traversal
Parameter onerror:
- If none, walk () ignores all oserror exceptions encountered during traversal
- Otherwise, it must be a function, with the exception OSError instance as a unique parameter, once walk () encounters an exception, it is passed to the onerror () function, onerror () can be freely defined.
Walk () Each generated item is a ternary group-(Dirpath, dirnames, filenames), where:
- Dirpath: The name of the directory that is currently traversed;
- dirnames: List that contains all the immediate subdirectory names of the current directory (excluding "." and "..") );
- filenames: A list that contains all the file names in the current directory;
Cases:
Import osfor Dirpath, Dirnames, filenames in Os.walk ("D:\\programs"): dirnames[:] = [D for D in Dirnames if n OT D.startswith ('. ') )] for name in filenames: print os.path.join (dirpath, name)
This example will print out all the files in the "D:\\programs" directory, all directories that do not start with ".",
Note that when Topdown is true, when traversing to a level directory, modifying the resulting dirnames list can affect the number and order of subdirectories that will be traversed in the next layer, for example, in this case, the "." Is removed. The beginning of the directory.
Python files and file systems (2)--os module support for file and file system operations