在python内置的open函数中,模式w , a , w+ , a+和r+的确切区别是什么?
特别地,文档暗示所有这些都将允许写入文件,并说它打开文件专门用于“追加”,“写入”和“更新”,但未定义这些术语的含义。
1.打开模式与C标准库函数fopen()完全相同。
BSD fopen联机帮助页对它们的定义如下:
<code>The argument mode points to a string beginningwith
oneof
thefollowing
sequences (Additionalcharacters
may follow these sequences.):``
r''
Open
text
file
for
reading. The streamis
positionedat
thebeginning
of
the file.``
r+''
Open
for
readingand
writing. The streamis
positionedat
thebeginning
of
the file.``
w''
Truncate
file
to
zerolength
or
create
text
file
for
writing. The streamis
positionedat
thebeginning
of
the file.``
w+''
Open
for
readingand
writing. Thefile
is
createdif
it doesnot
exist, otherwise itis
truncated. The streamis
positionedat
thebeginning
of
the file.``
a''
Open
for
writing. Thefile
is
createdif
it doesnot
exist. The streamis
positionedat
theend
of
the file. Subsequent writesto
thefile
willalways
end
upat
thethen
current
end
of
file
, irrespectiveof
any
intervening fseek(3
)or
similar.``
a+''
Open
for
readingand
writing. Thefile
is
createdif
it doesnot
exist. The streamis
positionedat
theend
of
the file. Subse- quent writesto
thefile
willalways
end
upat
thethen
current
end
of
file
, irrespectiveof
any
intervening fseek(3
)or
similar./<code>
2.这些选项与C标准库中的fopen函数相同:
1.w截断文件,覆盖已存在的文件
2.文件a追加,添加到已经存在的任何内容上
3.w+打开以进行读取和写入,截断文件,但也允许您回读已写入文件的内容
4.a+打开以进行追加和读取,使您既可以追加到文件,也可以读取其内容
3.我碰巧试图弄清楚为什么要使用模式“ w +”与“ w”。
最后,我只是做了一些测试。 我看不到'w +'模式有什么用,因为在两种情况下,文件都是从头开始被截断的。 但是,有了“ w +”,您可以在写完后通过回头阅读。 如果您尝试使用“ w”进行任何读取,都会引发IOError。 在模式“ w +”下不使用seek进行读取不会产生任何结果,因为文件指针将位于您写入的位置之后。
4.我注意到,我不时需要重新打开Google,只是为了构想两种模式之间的主要区别是什么。 因此,我认为下一次阅读图会更快。 也许其他人也会发现它也有帮助。
5.相同信息,只是表格形式
<code> | r r+ w w+ a a+ read | + + + + write | + + + + + write after seek | + + +create
| + + + +truncate
| + +position
at
start
| + + + +position
at
end
| + +/<code>
意义在哪里:(为避免任何误解)
1.读取-允许从文件读取
2.写-允许写入文件
3.create-如果尚不存在则创建文件
4.截断-在打开文件期间将其清空(删除了文件的所有内容)
5.开始位置-打开文件后,初始位置设置为文件的开始
6.末尾位置-打开文件后,将初始位置设置为文件末尾
注意: a和a+始终附加在文件末尾-忽略任何seek运动。
顺便说一句。 至少在我的win7 / python2.7上,对于以a+模式打开的新文件而言,有趣的行为是:
<code>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/<code>
最后
小编近几年在学习Python!对于想学习Python的朋友们,我想说:很多人学了一个星期就放弃了,为什么呢?其实没有好的学习资料给你去学习,你们是很难坚持的,这是小编收集的Python入门学习资料!