在python中打开文件时'r+'和'a+'有什么区别? [英] What's the difference between 'r+' and 'a+' when open file in python?
问题描述
我尝试了 r+
和 a+
打开文件和读写,但是 'r+' 和 'a+' 都将 str 附加到文件的末尾.
I have try r+
and a+
to open file and read and write, but 'r+' and 'a+' are all append the str to the end of the file.
那么,r+
和 a+
有什么区别?
So, what's the difference between r+
and a+
?
添加:
我找到了原因:
我已经阅读了文件对象,但忘记了 seek(0) 将位置设置为开始
I have read the file object and forgot to seek(0) to set the location to the begin
推荐答案
Python opens files almost in the same way as in C:
r+
为读写打开.流位于文件的开头.
r+
Open for reading and writing. The stream is positioned at the beginning of the file.
a+
打开以供读取和追加(在文件末尾写入).如果文件不存在,则创建该文件. 用于读取的初始文件位置在文件的开头,但输出会附加到文件的末尾(但在某些 Unix 系统中,无论当前搜索位置).
a+
Open for reading and appending (writing at end of file). The file is created if it does not exist. The initial file position for reading is at the beginning of the file, but output is appended to the end of the file (but in some Unix systems regardless of the current seek position).
这篇关于在python中打开文件时'r+'和'a+'有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!