In any language, file reads and writes are very common. Python file read and write is very simple, just a function open (file also can, but I do not use).
First look at the official website explanation:
Open (file, mode= ' R ', Buffering=-1, Encoding=none, Errors=none, Newline=none, Closefd=true, Opener=none)
Open file and return a stream. Raise IOError upon failure.
Common open Mode:
R can only read
R+ is readable and writable, does not create files that do not exist, writes from the top, overwrites content from the previous location
w+ readable writable, if the file exists, overwrites the entire file, does not exist then creates
W can only write, overwrite entire file, not exist then create
A can only be written, add content from the bottom of the file does not exist then create
A + readable writable read from the top of the file add content from the bottom of the file does not exist then create
But the experiment found that this is r+ 可读可写 不会创建不存在的文件 从顶部开始写 会覆盖之前此位置的内容
not complete.
The original files of the test.txt are as follows:
Good morning.
If we do not read or write after the open file, add it from the end
1 with open ('test.txt', mode='r+', encoding=' utf-8') as F:2 f.writelines (" Beijing " )
The file then becomes
Beijing Good Hello how is you?
If we read before writing, the file is added at the end
1 with open ('test.txt', mode='r+', encoding=' utf-8') as F:2 f.read (1)3 F.writelines (" Beijing ")
At this time at the end of the file to add Beijing two words, and we read how much does not matter. Acting like A + mode
Good morning. How is You? Beijing
Note: processing files in r+ mode makes it easy to mistake content, and be careful
If you open a file in w+ mode, the file is overwritten or rebuilt after you write it, the sample
1 with open ('test.txt', mode='w+', encoding=' utf-8') as F:2 f.write ("Tianjin" )3 f.flush ()4 print(F.readlines ())
Get empty []
With open ('test.txt', mode='w+', encoding=' Utf-8') as F: f.writelines (" Tianjin ") F.writelines (' Shandong ') f.flush () f.seek (0) Print(F.readlines ())
Seek is required to read the content that was just written.
Also note that the write operation does not automatically add a line break
There is a line break at the end of the read line and you can remove the line break with the ". Strip ().
With open ('test.txt', mode='r', encoding=' Utf-8') as F: for in f: print(line. Strip ()) Remove line breaks
Python3 file read and write mode