coding format
Common encoding formats:
- Python's interpreter uses Unicode (memory)
- .py files use UTF-8 on disk (external memory)
Changing the encoding format
The general form is to write # coding: coding format, # coding=coding format at the beginning of the program.
Principles of reading and writing files
- The reading and writing of files is commonly known as ''IO operations'' (input-output FIFO)
- File read and write operation flow
Principles of Operation:
The built-in function open() creates a file object:
Grammatical rules:
file = open('', 'r') # Create new documents print(()) # Reads and writes files; readlines reads a list of all the contents of a file. () # Close resources ------------------------------------------------------------------ ['China \n', 'Beautiful']
Commonly used file opening modes
Type of document
Files are divided into the following two broad categories according to the organization of the data in the file:
- **Text file.** stores universal ''character'' text, which defaults to the Unicode character set and can be opened using the Notepad program
- **Binary file:**The content of the data with ''bytes'' for storage, can not be opened with Notepad, you must use special software to open, for example: mp3 audio files, jpg pictures, .doc documents and so on.
Open mode | descriptive |
---|---|
r | To open a file in read-only mode, the pointer to the file will be placed at the beginning of the file. |
w | Open the file in write-only mode, if the file does not exist, create it; if the file exists, overwrite the original content, with the file pointer at the beginning of the file |
a | Open the file in append mode, if the file does not exist, it is created and the file pointer is at the beginning of the file; if the file exists, it is appended at the end of the file. |
b | Opens files in binary mode, cannot be used alone, needs to be used with other modes; rb or wb |
+ | Opens a file in read/write mode, cannot be used alone, needs to be used with other modes; a+ |
file = open('', 'r') # Create new documents print(()) # Reads and writes files; readlines reads a list of all the contents of a file. () # Close resources file = open('', 'w') ('Python') () file = open('', 'a') ('Python') () # Copy the file src_file = open('', 'rb') target_file = open('', 'wb') target_file.write(src_file.read()) target_file.close() src_file.close() 'wb') target_file.write(src_file.read()) target_file.close() src_file.close()
To this article on Python file reading and writing and commonly used file opening method is introduced to this article, more related Python file reading and writing and content, please search for my previous articles or continue to browse the following related articles I hope you will support me in the future!