File operation steps: 1. There is a file, 2. Open the file, 3. Read and write the modified file, 4. Close the file
One. one file: New or imported file
Two. Open file: If it is the new file default and the py file in the same directory, if it is open file, to put the file in the PY directory or open file to write absolute path
There are two ways to open a file: 1. f = open (' User.txt '); 2. With open (' User.txt ') as F, open (' User2.txt ') as F:
The difference between the two is that the 1th method must be closed with f.close (), the definition can only open one file at a time, the second method can be automatically closed, can be connected to multiple files simultaneously open
Four. Read, write, and modify files
1. File Mode Introduction
1) r Read Only mode, cannot write, file does not exist times wrong, open file not write mode, default read Only
2) W write mode cannot be read, overwrite the original file content when writing, and create a new file when the file does not exist
3) w+ write mode, can not read the content, nor error, but will clear the contents of the file
4) r+ can write content, can read, at the beginning of the file to write, will not overwrite the original file content, but when the file does not exist, will error
5) A append write, cannot read, will write the content at the end of the file, write without overwriting the original file content, the file does not exist when the new file is created
6) A + append mode, readable, will write the content at the end of the file, do not overwrite the original content, the file does not exist when the new file is created
1. Read the file, read the contents of the file is a string type
If the file pointer at the end, cannot read the contents of the file, you can specify the file pointer at the beginning with seek (0), to follow the read () before
read out the contents of the file and return a list
ReadLines (): reads all the contents of the file, returns a list, each of the files is a list of one element value
ReadLine (): reads only one row at a time, reads the data in the row of the pointer, returns no format, reads only the contents
2. Write files
3. Modify the file
Step: Open File-read file-replace file contents (replace)
4. Write the contents of the buffer to disk
Five. Close the file
F.close () or auto-off
Six. Efficient processing of files, looping through a single line of read-only files each time, ReadLine () can also implement a read-only one line at a time, but can not determine whether the file is read with a loop to
Seven. Documentation Exercises-monitoring logs
Eight. Working with JSON
Import Json:import.json
Convert JSON string format strings to dictionaries json.loads ()
Turn the dictionary into a string json.dumps ()
The difference between loads and load:
The difference between dump and dumps
Python Basics (iii) file manipulation and processing JSON