[英]Differences when accessing a file with Python?
Learning about different access methods that can be used when opening a file with Python. What is the difference between opening a file for both reading and writing vs. opening a file for both writing and reading?了解使用 Python 打开文件时可以使用的不同访问方法。打开文件进行读写与打开文件进行写入和读取有什么区别?
when using the open()
function you can use any any of these to open a file:使用open()
function 时,您可以使用其中任何一个打开文件:
my question is really would there be a different outcome when using either r+ vs w+ to open files?我的问题是使用 r+ 与 w+ 打开文件时真的会有不同的结果吗?
The difference between r+
and w+
is that w+
will empty the file first. r+
和w+
的区别在于w+
会先清空文件。 So you typically use r+
if you want to read the file first, then write to it.因此,如果您想先读取文件,然后写入文件,通常会使用r+
。 You use w+
if you want to write to the file first, then read what you've written.如果你想先写入文件,你可以使用w+
,然后读取你所写的内容。
a+
automatically positions to the end of the file when it's first opened and before every write. a+
在第一次打开文件时和每次写入之前自动定位到文件末尾。 So you can use it similarly to r+
, but you have to seek first if you want to read what's already in the file, and all writes are appended to the end.所以你可以像r+
一样使用它,但是如果你想读取文件中已有的内容,你必须先查找,并且所有写入都附加到末尾。
The modes without +
just allow reading or writing, not both.没有+
的模式只允许读取或写入,而不是两者。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.