被python文件模式“ w +”混淆

问题:被python文件模式“ w +”混淆

文档

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

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

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

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.

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.

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


回答 0

假设您打开的文件带有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'

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

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

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.


回答 1

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

  • [R

    打开一个文件以供只读。文件指针放置在文件的开头。这是默认模式。

  • rb

    打开文件以仅以二进制格式读取。文件指针放置在文件的开头。这是默认模式。

  • r +

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

  • rb +

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

  • w

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

  • b

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

  • w +

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

  • wb +

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

  • 一个

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

  • b

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

  • a +

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

  • ab +

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

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.


回答 2

Python中的所有文件模式

  • r 阅读
  • r+ 打开以进行读写(无法截断文件)
  • w 用于写作
  • w+ 用于读写(可以截断文件)
  • rb用于读取二进制文件。文件指针放置在文件的开头。
  • rb+ 读取或写入二进制文件
  • wb+ 编写二进制文件
  • a+ 打开进行追加
  • ab+打开一个文件,以附加和读取二进制文件。如果文件存在,则文件指针位于文件的末尾。该文件以追加模式打开。
  • x 打开以进行独占创建,如果文件已存在则失败(Python 3)

All file modes in Python

  • r for reading
  • r+ opens for reading and writing (cannot truncate a file)
  • w for writing
  • w+ for writing and reading (can truncate a file)
  • rb for 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.
  • x open for exclusive creation, failing if the file already exists (Python 3)

回答 3

r 供阅读

w

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

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

例如,

>>> 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
$

r for read

w for write

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

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

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
$

回答 4

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

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


回答 5

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

1)很明显,就是打开文件以供只读,将其读入内存,然后用t打开文件,然后写入更改。

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)

希望这可以帮助..

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.

2) use the low level file handling routines:

# 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..


回答 6

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

test.in 文件内容:

hello1
ok2
byebye3

和py脚本的:

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

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

hello1
ok2
byebye3
addition

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

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

test.in也做了回应:

additionk2
byebye3

所以 r+如果我们不执行读取操作模式将使我们从一开始就覆盖内容。而且,如果我们执行一些读取操作,f.write()则只会追加到文件中。

顺便说一下,如果我们f.seek(0,0)以前f.write(write_content)这样做过,write_content将从positon(0,0)覆盖它们。

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

test.in file’s content:

hello1
ok2
byebye3

And the py script’s :

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

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

hello1
ok2
byebye3
addition

However, when we modify the script to :

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

the test.in also do the respond:

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.

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).


回答 7

h4z3所述,为实际使用,有时您的数据太大而无法直接加载所有内容,或者您​​拥有生成器或实时传入的数据,则可以使用w +存储在文件中并在以后读取。

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.