Python file operations,
1. Open and Close a file
The open () function is used to open the file, and the close () function is used to close the file.
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None):
File: The name of a string or an array. The file name can be relative to the current directory or absolute path.
Mode: Specifies the file opening mode. The default value is'r'。
| Character |
Description |
'r' |
Open Reading (default) |
'w' |
Open the write, first truncate the file |
'x' |
Open for exclusive creation. failed if the file already exists |
'a' |
Open for writing. If yes, It is appended to the end of the file. |
'b' |
Binary Mode |
't' |
Text mode (default) |
'+' |
Open the disk file for update (read/write) |
'U' |
General Line Break mode (obsolete) |
Encoding: name used to decode or encode a file, for example, 'utf-8'
Other parameters are not commonly used.
Close (): When you use a file, you can call the close () method to close it and release all system resources it occupies.
f.close()
Example of opening or closing a file:
f=open('text.log','r',encoding= 'utf-8')f.close()
With statement:
To avoid forgetting to close a file after it is opened, you can manage the file by managing the context, for example:
with open('text.log','r',encoding= 'utf-8') as file_ex : print(file_ex.read()) pass
You can also manage multiple files at the same time, for example:
with open('text.log','r',encoding= 'utf-8') as file_ex ,open('text2.log','r',encoding= 'utf-8') as file_ex2 : pass
2. file read/write operations
3. Other File Operations