Home >Backend Development >Python Tutorial >Characteristics and differences of the three readable and writable modes of Python files

Characteristics and differences of the three readable and writable modes of Python files

不言
不言forward
2018-10-09 16:38:214765browse

This article brings you the characteristics and differences of the three readable and writable modes of Python files. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

This article mainly discusses the characteristics of the three readable and writable modes of files and the differences between them, as well as whether the operation of modifying files can be realized

Becauseprevious article We have already discussed encoding, so we will not study encoding here. All open operations default to utf-8 encoding (under Linux system)

First we look at r (read and write)

Since r can both read and write, is it possible to modify files in r mode? The answer is yes! , however, one thing you need to note is that unless you know the exact content to be modified at the exact location, you will often not get the results you expect. An example is as follows:
We have such a text "Kill one person in ten steps, leave no trace in a thousand miles"
Suppose there is such a demand, change "Kill one person in ten steps" to "Kill a bandit in ten steps", The initial idea is: use read(4) to read the Chinese character "一", and then write the Chinese character "一bandit":

with open('job', mode='r+') as f:
    print('先读取四个字符:',f.read(4))
    print('读取后的指针位置:',f.tell())
    f.write('个土匪')
    f.seek(0)
    print(f.read())
    输出为:
    先读取四个字符: 十步杀一
    读取后的指针位置: 12
    十步杀一人,千里不留行个土匪

As you can see from the results, the pointer is indeed moved to the specified point using read(4) position, but when writing, it did not go as expected, but ran to the end of the file. This reason involves something called "CHUNK". Teacher Andi didn't teach it, so I can't explain it in depth. I'll tell you about it after I deeply understand it.

The above is the detailed content of Characteristics and differences of the three readable and writable modes of Python files. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete

Related articles

See more