Python OS Module Library Explained
os stands for "operating system", and as the name implies, the os module provides an interface for various Python programs to interact with the operating system. Using the os module makes it easy to interact with the operating system on the one hand, and greatly enhances the portability of your code on the other. If something goes wrong with a function in this module, an OSError exception or its subclasses will be thrown.
take note of
If you are reading or writing files, it is recommended to use the built-in function open();
For path-related operations, it is recommended to use the os submodule;
If you want to read multiple files line by line, it is recommended to use the fileinput module;
To create temporary files or paths, it is recommended to use the tempfile module;
For more advanced file and path manipulation the shutil module should be used.
List of common Python OS functions
function (math.) | descriptive |
---|---|
Replaces the operating system-specific path separator | |
Indicates the platform you are working with. For example, for Windows it's 'nt' and for Linux/Unix users it's 'posix'. | |
Get the current working directory, i.e. the path to the directory where the current python script is working. | |
() and | are used to read and set environment variables, respectively |
() | Returns all files and directory names in the specified directory |
(file) | Delete a file |
(file) | Getting File Properties |
(file) | Modifying file permissions and timestamps |
(name) | Create a catalog |
(name) | Delete Catalog |
(r“c:\python”) | Delete multiple directories |
() | Run the shell command |
() | Terminate the current process |
Gives the line terminator for the current platform. For example, Windows uses '\r\n', Linux uses '\n' and Mac uses '\r' | |
() | Returns the directory name and filename of a path |
() and () | Check whether the given path is a directory or a file, respectively. |
() | Check if the given path really exists |
(dirname) | List directories and files under dirname |
() | Get the current working directory |
Return to current directory ('.') | |
(dirname) | Change working directory to dirname |
(name) | Determine whether name is a directory or not, and return false if it is not. |
(name) | Determine whether the file name exists, return false if it doesn't. |
(name) | Determine if file or directory name exists |
(name) | or the size of the file, if name is a directory return 0L |
(name) | Get absolute path |
() | Determine if the path is absolute |
(path) | Standardized path string form |
(name) | Split filenames from directories (in fact, if you use directories exclusively, it also splits the last directory as a filename, and it doesn't determine if a file or directory exists) |
() | Separate file names and extensions |
(path,name) | Linking directories with filenames or directories |
(path) | Returns the file name |
(path) | Returns the file path |
Python OS module library open mode
(""): create empty file
fp = open("",w): open a file directly, create the file if it does not exist
paradigm | descriptive |
---|---|
w | writing style |
a | Append mode open (start at EOF, create new file if necessary) |
r+ | Open in read/write mode |
w+ | Open in read/write mode |
a+ | Open in read/write mode |
rb | Open in binary read mode |
wb | Open in binary write mode (see w ) |
ab | Open in binary append mode (see a ) |
rb+ | Open in binary read/write mode (see r+ ) |
wb+ | Open in binary read/write mode (see w+ ) |
ab+ | Open in binary read/write mode (see a+ ) |
Python OS Module Library File Manipulation
methodologies | descriptive |
---|---|
([size]) | size is the length of the read in bytes. |
([size]) | Read a line, if size is defined, it is possible that only a part of the line is returned. |
([size]) | Treats each line of the file as a member of a list, and returns the list. it is actually implemented internally by calling readline() in a loop. If the size parameter is provided, size is the total length of the read content, which means that only a part of the file may be read. |
(str) | To write str to a file, write() doesn't put a newline after str. |
(seq) | Writes the entire contents of the seq to the file (multiple lines at once). This function also just writes faithfully, without adding anything after each line. |
() | Close files. python will automatically close a file when it is not in use, but this feature is not guaranteed and it is best to get in the habit of closing files yourself. If you operate on a file after it has been closed, a ValueError is thrown. |
() | Write the contents of the buffer to the hard disk |
() | Returns a long integer "file label". |
() | Whether the file is a terminal device file (in unix systems) |
() | Returns the current position of the file operation marker, originating at the beginning of the file |
() | Returns the next line and displaces the file operation marker to the next line. When you use a file in a statement like for ... in file, you are calling the next() function to implement traversal. |
(offset[,whence]) | Moves the file hit operation marker to the position of offset. This offset is usually calculated relative to the beginning of the file, and is usually a positive number. But if you provide whence parameter is not necessarily, whence can be 0 means from the beginning of the calculation, 1 means to the current position as the origin of the calculation. 2 means to the end of the file as the origin of the calculation. Note that if the file is opened in a or a+ mode, the file operation marker will automatically return to the end of the file each time a write operation is performed. |
([size]) | Cuts the file to a specified size, by default to the current file operation marker. If the size is larger than the file size, depending on the system, the file may be left unchanged, or the file may be padded with zeros to the appropriate size, or some random content may be added. |
Python OS Module Library Catalog Operations
function (math.) | descriptive |
---|---|
(“file”) | Create a catalog |
(“oldfile”,”newfile”) | Copying files: both oldfile and newfile can only be files. |
(“oldfile”,”newfile”) | oldfile can only be a folder, newfile can be a file or a destination directory |
(“olddir”,”newdir”) | Copy the folder.olddir and newdir both can only be directories, and newdir must not exist |
(“oldname”,”newname”) | Rename a file (directory). Files or directories are renamed using this command |
(“oldpos”,”newpos”) | Moving files (directories) |
(“dir”) | Only empty directories can be deleted |
(“dir”) | Empty directories and directories with content can be deleted. |
(“path”) | Convert directory, change path |
Examples of Python OS Module Libraries
Introduction of OS standard module library
#!/usr/bin/env python import os print () # Get current path print ('/mnt') # List all directories and files under /mnt print ('lala') # Create directories lala and haha print ('haha') print ('haha') # Delete haha print ('','') #Modify the file name
The results are as follows
root@ruanyang-HP-ProDesk-680-G2-MT:/mnt/python# python /mnt/python ['proc', 'perl_bash', 'docker', 'warn', 'blog', 'python', 'hostname', 'test', 'tags', 'perl_DB', 'shell', 'perl_test', '.vimrc~', '', '', '.vimrc'] None None None None root@ruanyang-HP-ProDesk-680-G2-MT:/mnt/python# ls lala os_file.py
(1) Return operating system type
The value posix is the linux operating system.
The value nt is the windows operating system
(2) () Operating system details
info = () print(info) print() print()
(3) Return the system's environment variables
print() print(('PATH')) #pass (a bill or inspection etc)keyThe value is obtained from the environment variable corresponding to thevalue(be) worth
(4) () to determine whether the path is an absolute path
Paths from root are absolute paths and do not determine if a file exists or not
print(('/tmp/gfff')) print((''))
(5) Generate absolute paths
print(('')) print((('.'),'hello')) print(('/home/kiosk',''))
(6) Get directory name and file name
filename = '/home/home/Desktop/filename' print((filename)) # Get filename filename print((filename)) #gainfilenamecatalog name
(7) Create a catalog
('img') # Create a catalog ('img/dir1/dir2') # Recursively create directories # Can't recursively delete directories ('img')
(8) Creation of documents and deletion of documents
('00_ok.txt') #Creating files ('00_ok.txt') #Delete file
(9) File renaming
('','') #Rename the file to
(10) Determine if a file or directory exists
print((''))
(11) Separation of suffixes and filenames
print((''))
(12) Separate directory names from file names
print(('/tmp/hello/'))
(13) Get the time stamp of the last modification of the document
print(('/etc/group'))
This article introduces the python standard library OS module function list and examples of the full solution, more about the python standard library OS module knowledge please see the following related links