Python_file opening and closing

        Python has a built-in open() method for reading and writing files. Using the open() method can be divided into three steps, one is to open the file, the other is to operate the file, and the third is to close the file.

        The return value of the open() method is a file object, which can be assigned to a variable (file handle). Its basic syntax format is: f = open(filename,mode), filename: file name, mode: open mode; close: f.close().

Open method parameters:

r: Open the file in read-only mode, the file pointer will be placed at the beginning of the file, which is the default mode.

w: Open a file for writing only, overwrite the file if it already exists, or create a new file if the file does not exist

a: Open a file for appending. If the file already exists, the file pointer will be placed at the end of the file, that is, the new content will be written after the existing content; if the file does not exist, create it The new file is written.

rb: Open a file in binary format for read-only, the file pointer will be placed at the beginning of the file, this is the default mode.

wb: Open a file in binary format only for writing, if the file already exists, it will be overwritten; if the file does not exist, a new file will be created.

ab: Open a file in binary format for appending. If the file already exists, the file pointer will be placed at the end of the file, that is, the new content will be written after the existing content; if the file does not exists, create a new file for writing.

r+: Open a file for reading and writing, the file pointer will be placed at the beginning of the file.

w+: Open a file for reading and writing, if the file already exists, it will be overwritten; if the file does not exist, a new file will be created.

a+: Open a file for reading and writing. If the file already exists, the file pointer will be placed at the end of the file, and the file will be opened in append mode; if the file does not exist, create a new file for reading and writing.

rb+: Open a file in binary format for reading and writing, the file pointer will be placed at the beginning of the file.

wb+: Open a file in binary format for reading and writing, overwrite the file if it already exists; create a new file if the file does not exist.

ab+: Open a file in binary format for appending. If the file already exists, the file pointer will be placed at the end of the file; if the file does not exist, create a new file for reading and writing.

Guess you like

Origin blog.csdn.net/qq_52119661/article/details/128700780