程序员文章、书籍推荐和程序员创业信息与资源分享平台

网站首页 > 技术文章 正文

python打开内置函数:模式a,a +,w,w +和r +之间的区别?

hfteth 2024-12-17 11:38:26 技术文章 28 ℃

在python内置的open函数中,模式w , a , w+ , a+和r+的确切区别是什么?

特别地,文档暗示所有这些都将允许写入文件,并说它打开文件专门用于“追加”,“写入”和“更新”,但未定义这些术语的含义。

1.打开模式与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.

2.这些选项与C标准库中的fopen函数相同:

1.w截断文件,覆盖已存在的文件

2.文件a追加,添加到已经存在的任何内容上

3.w+打开以进行读取和写入,截断文件,但也允许您回读已写入文件的内容

4.a+打开以进行追加和读取,使您既可以追加到文件,也可以读取其内容

3.我碰巧试图弄清楚为什么要使用模式“ w +”与“ w”。

最后,我只是做了一些测试。 我看不到'w +'模式有什么用,因为在两种情况下,文件都是从头开始被截断的。 但是,有了“ w +”,您可以在写完后通过回头阅读。 如果您尝试使用“ w”进行任何读取,都会引发IOError。 在模式“ w +”下不使用seek进行读取不会产生任何结果,因为文件指针将位于您写入的位置之后。


4.我注意到,我不时需要重新打开Goog??le,只是为了构想两种模式之间的主要区别是什么。 因此,我认为下一次阅读图会更快。 也许其他人也会发现它也有帮助。


5.相同信息,只是表格形式

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

意义在哪里:(为避免任何误解

1.读取-允许从文件读取

2.写-允许写入文件

3.create-如果尚不存在则创建文件

4.截断-在打开文件期间将其清空(删除了文件的所有内容)

5.开始位置-打开文件后,初始位置设置为文件的开始

6.末尾位置-打开文件后,将初始位置设置为文件末尾

注意: a和a+始终附加在文件末尾-忽略任何seek运动。

顺便说一句。 至少在我的win7 / python2.7上,对于以a+模式打开的新文件而言,有趣的行为是:

write('aa'); seek(0, 0); read(1); write('b') write('aa'); seek(0, 0); read(1); write('b') -第二次write被忽略 
write('aa'); seek(0, 0); read(2); write('b') write('aa'); seek(0, 0); read(2); write('b') -第二次write引发IOError

最后

小编近几年在学习Python!对于想学习Python的朋友们,我想说:很多人学了一个星期就放弃了,为什么呢?其实没有好的学习资料给你去学习,你们是很难坚持的,这是小编收集的Python入门学习资料!

Tags:

最近发表
标签列表