Home  >  Article  >  Backend Development  >  Detailed explanation of the usage of open function in python

Detailed explanation of the usage of open function in python

hzc
hzcOriginal
2020-06-22 16:08:3710733browse

Detailed explanation of the usage of open function in python

Detailed explanation of the usage of open function in python

python open() function is used to open a file and create a file object. Only relevant methods can be called to read and write.

The syntax of the function is:

open(name[, mode[, buffering]])

Parameter description:

  • ##name: a string containing the name of the file you want to access value.

  • mode : mode determines the mode of opening the file: read-only, write, append, etc. See the complete list of all possible values ​​below. This parameter is optional and the default file access mode is read-only (r).

  • buffering : If the buffering value is set to 0, there will be no buffering. If buffering has a value of 1, lines will be buffered when accessing the file. If the buffering value is set to an integer greater than 1, it indicates that this is the buffer size of the register area. If it takes a negative value, the buffer size of the register area is the system default.

The basic value of the parameter Mode

r, w, and a are the basic modes for opening files, corresponding to read-only, write-only, Append mode; the four characters

b, t, and U are used in combination with the above file opening modes. Binary mode, text mode, read-write mode, and universal newline character are used in combination according to the actual situation.

Common mode value combinations

1、r或rt     默认模式,文本模式读
2、rb      二进制文件
3、w或wt     文本模式写,打开前文件存储被清空
4、wb      二进制写,文件存储同样被清空 
5、a       追加模式,只能写在文件末尾
6、a+       可读写模式,写只能写在文件末尾 
7、w+      可读写,与a+的区别是要清空文件内容
8、r+      可读写,与a+的区别是可以写到文件任何位置

Recommended tutorial: "

Python Tutorial"

The above is the detailed content of Detailed explanation of the usage of open function in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn