Operation of files for basic introduction to python

**python** file operation 
1. Open the file
Open the file: open(file, mode='r')
file: the path of the operation file plus the file name
#absolute path: starting from the root directory
#relative path: from a certain The path starts
mode: the mode (permission) of the file to open
the file permission:
r(read): read
w(write): write
a(apped): append
Read, or write
r+: read and write, do not create a new file, the file read and write pointer is at the beginning
w+: read and write, create a new file, the read and write pointer is at the beginning, if the file exists, overwrite the original content of the file
a+: read and write, Create a new file, the read and write pointer is at the end, and the previous file will not be overwritten.
With write permission, when a non-existing file is opened, the file is created
2. Read and write file
* read file *
str = read([num]) When reading a file, you can specify the number of bytes to read or do not specify
**read-write pointer**:
when the file is read and written, the disk will temporarily put the file in the memory, and the pointer will be shared when reading and writing the file.
The file.seek(offset[,whence]) function can modify the file position pointer
offset: offset
whence: offset position, 0 from the beginning of the file, 1 from the current position, 2, from the end of the file
***Note** *If the file is opened in a or a+ mode, the file operation flag will automatically
return to the end of the file every time a write operation is performed
*** Move the pointer to the beginning of the file Function: file.seek(0,0)
str = readLine() Read a line of strings
list = readLines(num) Read multiple lines and return to a list
**Write a file**
write('str'): Write a string in a file
This method does not join at the end of the string '\n' newline symbol, and when writing, it will prompt the number of bytes written
file.flush(): flush the content in the buffer to the disk, you can also use file.close() to flush Buffer
file.writelines(list_of_string): write a list of strings to a file

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325124500&siteId=291194637
Recommended