内置open函数中a、a+、w、w+和r+模式的区别是什么?

862 投票
9 回答
751486 浏览
提问于 2025-04-15 14:32

在Python内置的open函数中,模式waw+a+r+之间到底有什么具体的区别呢?

特别是,文档中提到这些模式都可以用来写入文件,并且特别说明它们是用来“追加”、“写入”和“更新”文件的,但并没有详细解释这些术语的意思。

9 个回答

304

这些信息以表格的形式呈现

                  | r   r+   w   w+   a   a+
------------------|--------------------------
read              | +   +        +        +
write             |     +    +   +    +   +
write after seek  |     +    +   +
create            |          +   +    +   +
truncate          |          +   +
position at start | +   +    +   +
position at end   |                   +   +

其中的意思是:

  • read - 允许从文件中读取数据

  • write - 允许向文件中写入数据

  • create - 如果文件不存在,就会创建一个新文件

  • truncate - 打开文件时,会把文件内容清空(所有内容都会被删除)

  • position at start - 打开文件后,初始位置设置在文件的开头

  • position at end - 打开文件后,初始位置设置在文件的末尾

注意:aa+ 模式总是会在文件末尾追加内容 - 不管你怎么移动位置,都会忽略这些移动。
顺便说一下,在我的win7 / python2.7上,使用 a+ 模式打开新文件时,有个有趣的行为:
write('aa'); seek(0, 0); read(1); write('b') - 第二个 write 被忽略
write('aa'); seek(0, 0); read(2); write('b') - 第二个 write 会引发 IOError

827

我发现有时候我需要重新在网上查一下fopen的用法,才能记起不同模式之间的主要区别。所以,我想做个图,这样下次看起来会更快一些。也许其他人也会觉得这个有用。

986

打开文件的方式和C语言标准库中的fopen()函数是完全一样的。

BSD的fopen手册对这些打开方式的定义如下:

 The argument mode points to a string beginning with one of the following
 sequences (Additional characters may follow these sequences.):

 ``r''   Open text file for reading.  The stream is positioned at the
         beginning of the file.

 ``r+''  Open for reading and writing.  The stream is positioned at the
         beginning of the file.

 ``w''   Truncate file to zero length or create text file for writing.
         The stream is positioned at the beginning of the file.

 ``w+''  Open for reading and writing.  The file is created if it does not
         exist, otherwise it is truncated.  The stream is positioned at
         the beginning of the file.

 ``a''   Open for writing.  The file is created if it does not exist.  The
         stream is positioned at the end of the file.  Subsequent writes
         to the file will always end up at the then current end of file,
         irrespective of any intervening fseek(3) or similar.

 ``a+''  Open for reading and writing.  The file is created if it does not
         exist.  The stream is positioned at the end of the file.  Subse-
         quent writes to the file will always end up at the then current
         end of file, irrespective of any intervening fseek(3) or similar.

撰写回答