Python file read-write mode


File common read-write mode
w opened for writing,
W file if there is, we must first empty, then (re) create
a opened in append mode (from EOF start, create a new file if necessary)
r + in read-write mode open
w + to read-write mode opening (see W)
A + opened in read-write mode (see A)
RB is opened in binary read mode
wb binary opened in write mode (see W)
ab & additionally opened in binary mode (see A)
RB + binary write mode open (see + R & lt)
WB + opened in binary read-write mode (see + W)
ab & + opened in binary read-write mode (see a +)

 


Read the contents of the file
open read all the contents
after opening the file using the open must remember to close the file object call () method.
= Open File ( 'thefile.txt')
File.close ()

 

Open with ( 'ecord.txt', '+ A', encoding = 'UTF-. 8') AS F:
     f.write (STR + '\ n-')
write complete shut down automatically

 

Write
the file_object = Open ( 'thefile.txt', 'W')
file_object.write (all_the_text)
file_object.close ()
to write a text file
output = open ( 'data', 'w')

 

Writing binary
output = open ( 'data', 'wb')
additionally write file
output = open ( 'data', 'w +')

 

Write multiple lines
file.writelines (strings)

 

Note that calling writelines written on multi-line performance than write to write-once high.

 


File open mode w + r + a + difference and discrimination
w + opens the file and write:

 

  1. file exists, the empty (i.e., write null);

 

  2. The file does not exist, create a file;

 

  3. File positions the stream to the start position, the read () will be empty.
r + Open file and write:

 

    1. file exists, open the file, the file pointer is positioned to the beginning of the file;

 

  2. The file does not exist, an error file does not exist.
a + Open file and write:

 

    1. file exists, open a file, the file pointer is positioned to the start position, but not empty;

 

  2. The file does not exist, create a file;

 

  3. Open after reading the beginning of the file location,

 

  4. 写入时,添加到文章末尾,并且指针位于添加后的末尾,所以再次读取会乱码。
另外:
  1. w 打开文件写入,也会清空文件,如果使用read(),则报错;a 打开文件添加,数据流添加到文件末尾,而不是w模式的清空后,添加到文件末尾。
  2. b可以附加到上述的字母后,形成rb, rb+, wb等等模式,针对二进制文件,比如exe, elf, jpeg格式的文件,进行文件操作; 在unix 类型的系统上,text格式与二进制的处理相同,但是非unix类型的系统上,换行格式不同,所以需要用加b模式来在指定是否是二进制。

Guess you like

Origin blog.csdn.net/cy413026/article/details/90610633
Recommended