被python文件模式“w+”弄糊涂了

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16208206/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:01:31  来源:igfitidea点击:

Confused by python file mode "w+"

pythonfileio

提问by holys

From the doc,

文档中

Modes 'r+', 'w+' and 'a+' open the file for updating (note that 'w+' truncates the file). Append 'b' to the mode to open the file in binary mode, on systems that differentiate between binary and text files; on systems that don't have this distinction, adding the 'b' has no effect.

模式“r+”、“w+”和“a+”打开文件进行更新(注意“w+”会截断文件)。在区分二进制和文本文件的系统上,将“b”附加到模式以二进制模式打开文件;在没有这种区别的系统上,添加“b”无效。

and here

w+ : Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.

w+ :打开文件进行读写。如果文件存在,则覆盖现有文件。如果文件不存在,则创建一个新文件进行读写。

But, how to read a file open with w+?

但是,如何读取打开的文件w+

采纳答案by rmunn

Let's say you're opening the file with a withstatement like you should be. Then you'd do something like this to read from your file:

假设您正在使用with您应该使用的语句打开文件。然后你会做这样的事情来从你的文件中读取:

with open('somefile.txt', 'w+') as f:
    # Note that f has now been truncated to 0 bytes, so you'll only
    # be able to read data that you write after this point
    f.write('somedata\n')
    f.seek(0)  # Important: return to the top of the file before reading, otherwise you'll just read an empty string
    data = f.read() # Returns 'somedata\n'

Note the f.seek(0)-- if you forget this, the f.read()call will try to read from the end of the file, and will return an empty string.

请注意f.seek(0)-- 如果您忘记了这一点,该f.read()调用将尝试从文件末尾读取,并返回一个空字符串。

回答by Elazar

The file is truncated, so you cancall read()(no exceptions raised, unlike when opened using 'w') but you'll get an empty string.

该文件被截断,因此您可以调用read()(不会引发异常,与使用 'w' 打开时不同)但您将获得一个空字符串。

回答by Dory Zidon

I suspect there are two ways to handle what I think you'r trying to achieve.

我怀疑有两种方法可以处理我认为您想要实现的目标。

1) which is obvious, is open the file for reading only, read it into memory then open the file with t, then write your changes.

1)这是显而易见的,打开文件只读,将其读入内存,然后用 t 打开文件,然后写入您的更改。

2) use the low level file handling routines:

2) 使用低级文件处理例程:

# Open file in RW , create if it doesn't exist. *Don't* pass O_TRUNC
 fd = os.open(filename, os.O_RDWR | os.O_CREAT)

Hope this helps..

希望这可以帮助..

回答by Alok Agarwal

All file modes in Python

Python中的所有文件模式

  • rfor reading
  • r+opens for reading and writing (cannot truncate a file)
  • wfor writing
  • w+for writing and reading (can truncate a file)
  • rbfor reading a binary file. The file pointer is placed at the beginning of the file.
  • rb+reading or writing a binary file
  • wb+writing a binary file
  • a+opens for appending
  • ab+Opens a file for both appending and reading in binary. The file pointer is at the end of the file if the file exists. The file opens in the append mode.
  • xopen for exclusive creation, failing if the file already exists (Python 3)
  • r阅读
  • r+打开以进行读取和写入(无法截断文件)
  • w写作
  • w+用于写入和读取(可以截断文件)
  • rb用于读取二进制文件。文件指针位于文件的开头。
  • rb+读取或写入二进制文件
  • wb+写入二进制文件
  • a+打开以供追加
  • ab+打开一个文件以二进制追加和读取。如果文件存在,则文件指针位于文件末尾。文件以追加模式打开。
  • x打开以进行独占创建,如果文件已存在则失败(Python 3)

回答by Nullify

Here is a list of the different modes of opening a file:

以下是打开文件的不同模式的列表:

  • r

    Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.

  • rb

    Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the default mode.

  • r+

    Opens a file for both reading and writing. The file pointer will be at the beginning of the file.

  • rb+

    Opens a file for both reading and writing in binary format. The file pointer will be at the beginning of the file.

  • w

    Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.

  • wb

    Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.

  • w+

    Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.

  • wb+

    Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.

  • a

    Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.

  • ab

    Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.

  • a+

    Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.

  • ab+

    Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.

  • r

    以只读方式打开文件。文件指针位于文件的开头。这是默认模式。

  • RB

    以二进制格式打开一个只读文件。文件指针位于文件的开头。这是默认模式。

  • r+

    打开文件以进行读取和写入。文件指针将位于文件的开头。

  • RB+

    以二进制格式打开一个文件进行读写。文件指针将位于文件的开头。

  • 打开一个仅用于写入的文件。如果文件存在,则覆盖该文件。如果文件不存在,则创建一个新文件进行写入。

  • 打开一个仅以二进制格式写入的文件。如果文件存在,则覆盖该文件。如果文件不存在,则创建一个新文件进行写入。

  • w+

    打开文件以进行写入和读取。如果文件存在,则覆盖现有文件。如果文件不存在,则创建一个新文件进行读写。

  • 白+

    以二进制格式打开一个文件进行读写。如果文件存在,则覆盖现有文件。如果文件不存在,则创建一个新文件进行读写。

  • 一种

    打开要追加的文件。如果文件存在,则文件指针位于文件末尾。也就是说,文件处于追加模式。如果文件不存在,它会创建一个新文件用于写入。

  • AB

    打开一个文件以二进制格式追加。如果文件存在,则文件指针位于文件末尾。也就是说,文件处于追加模式。如果文件不存在,它会创建一个新文件用于写入。

  • 一个+

    打开一个文件以进行追加和读取。如果文件存在,则文件指针位于文件末尾。文件以追加模式打开。如果文件不存在,它会创建一个新文件进行读写。

  • ab+

    打开一个文件,以二进制格式进行追加和读取。如果文件存在,则文件指针位于文件末尾。文件以追加模式打开。如果文件不存在,它会创建一个新文件进行读写。

回答by Find

Actually, there's something wrong about all the other answers about r+mode.

实际上,关于r+模式的所有其他答案都有问题。

test.infile's content:

test.in文件内容:

hello1
ok2
byebye3

And the py script's :

和 py 脚本的:

with open("test.in", 'r+')as f:
    f.readline()
    f.write("addition")

Execute it and the test.in's content will be changed to :

执行它,test.in的内容将更改为:

hello1
ok2
byebye3
addition

However, when we modify the script to :

但是,当我们将脚本修改为:

with open("test.in", 'r+')as f:
    f.write("addition")

the test.inalso do the respond:

test.in也做了回应:

additionk2
byebye3

So, the r+mode will allow us to cover the content from the beginning if we did't do the read operation. And if we do some read operation, f.write()will just append to the file.

因此,r+如果我们不进行读取操作,该模式将允许我们从头开始覆盖内容。如果我们做一些读操作,f.write()只会追加到文件中。

By the way, if we f.seek(0,0)before f.write(write_content), the write_content will cover them from the positon(0,0).

顺便说一句,如果我们f.seek(0,0)之前f.write(write_content),write_content 将从位置(0,0)覆盖它们。

回答by SmartManoj

As mentioned by h4z3, For a practical use, Sometimes your data is too big to directly load everything, or you have a generator, or real-time incoming data, you could use w+ to store in a file and read later.

正如h4z3提到的,对于实际使用,有时你的数据太大而不能直接加载所有东西,或者你有一个生成器,或者实时传入的数据,你可以使用 w+ 存储在一个文件中,稍后阅读。

回答by GraceMeng

rfor read

r供阅读

wfor write

w

r+for read/write without deleting the original content if file exists, otherwise raise exception

r+如果文件存在,则用于读/写而不删除原始内容,否则引发异常

w+for delete the original content then read/write if file exists, otherwise create the file

w+删除原始内容然后读/写如果文件存在,否则创建文件

For example,

例如,

>>> with open("file1.txt", "w") as f:
...   f.write("ab\n")
... 
>>> with open("file1.txt", "w+") as f:
...   f.write("c")
... 

$ cat file1.txt 
c$
>>> with open("file2.txt", "r+") as f:
...   f.write("ab\n")
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'file2.txt'

>>> with open("file2.txt", "w") as f:
...   f.write("ab\n")
... 
>>> with open("file2.txt", "r+") as f:
...   f.write("c")
... 

$ cat file2.txt 
cb
$