Difference between open and codecs.open in Python
文章推薦指數: 80 %
open accepts encoding and newline parameters and interprets them as Python 3 does. Unlike codecs.open , a file opened with io.open will raise TypeError: write() ...
Home
Public
Questions
Tags
Users
Companies
Collectives
ExploreCollectives
Teams
StackOverflowforTeams
–Startcollaboratingandsharingorganizationalknowledge.
CreateafreeTeam
WhyTeams?
Teams
CreatefreeTeam
Collectives™onStackOverflow
Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost.
LearnmoreaboutCollectives
Teams
Q&Aforwork
Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch.
LearnmoreaboutTeams
Differencebetweenopenandcodecs.openinPython
AskQuestion
Asked
11years,7monthsago
Modified
2years,10monthsago
Viewed
89ktimes
118
TherearetwowaystoopenatextfileinPython:
f=open(filename)
And
importcodecs
f=codecs.open(filename,encoding="utf-8")
Wheniscodecs.openpreferabletoopen?
pythonunicodecodec
Share
Follow
editedApr12,2018at4:51
dreftymac
30.3k2626goldbadges115115silverbadges178178bronzebadges
askedMar9,2011at18:56
BlogueroConnorBlogueroConnor
1,81344goldbadges1717silverbadges1818bronzebadges
4
53
Notethatcodecs.open()isobsoletein3.x,sinceopen()gainsanencodingargument.
– IgnacioVazquez-Abrams
Mar9,2011at19:05
There'salsoa3rdway(inPython2.xatleast):`f=file(filename)'
– AdamParkin
Nov1,2012at15:53
1
@IgnacioVazquez-AbramsIsthereanylinkthatcodecs.open()isobsolete?Idon'tthinkthisinpython3docs:docs.python.org/3.7/library/codecs.html
– varela
Apr17,2019at12:25
1
@varela:thePythondocumentationpageyoumentionedsays:"thebuiltinopen()andtheassociatediomodulearetherecommendedapproachforworkingwithencodedtextfiles"
– LucianoRamalho
May10,2019at2:10
Addacomment
|
7Answers
7
Sortedby:
Resettodefault
Highestscore(default)
Trending(recentvotescountmore)
Datemodified(newestfirst)
Datecreated(oldestfirst)
89
SincePython2.6,agoodpracticeistouseio.open(),whichalsotakesanencodingargument,likethenowobsoletecodecs.open().InPython3,io.openisanaliasfortheopen()built-in.Soio.open()worksinPython2.6andalllaterversions,includingPython3.4.Seedocs:http://docs.python.org/3.4/library/io.html
Now,fortheoriginalquestion:whenreadingtext(including"plaintext",HTML,XMLandJSON)inPython2youshouldalwaysuseio.open()withanexplicitencoding,oropen()withanexplicitencodinginPython3.DoingsomeansyougetcorrectlydecodedUnicode,orgetanerrorrightoffthebat,makingitmucheasiertodebug.
PureASCII"plaintext"isamythfromthedistantpast.ProperEnglishtextusescurlyquotes,em-dashes,bullets,€(eurosigns)andevendiaeresis(¨).Don'tbenaïve!(Andlet'snotforgettheFaçadedesignpattern!)
BecausepureASCIIisnotarealoption,open()withoutanexplicitencodingisonlyusefultoreadbinaryfiles.
Share
Follow
editedMay1,2017at1:25
communitywiki
3revsLucianoRamalho
3
6
@ForeverWintrTheanswerisprettyclearlyinthere:useio.open()fortext,andopen()onlyforbinary.Theimplicationisthatcodecs.open()isnotpreferredatall.
– Bdoserror
Apr4,2017at18:11
4
@Bdoserror,Thereisananswerinthere,clearly,butit'snotananswertothequestionthatwasasked.Thequestionwasaboutthedifferencebetweenopenandcodecs.open,andspecificallywhenthelatterispreferabletotheformer.Ananswerthatdoesn'tsomuchasmentioncodecs.opencan'tanswerthatquestion.
– ForeverWintr
Apr4,2017at18:30
4
@ForeverWintrIfthetheOPaskedthewrongquestion(i.e.withtheassumptionthatcodecs.open()wascorrecttouse)thenthereisno"correct"answeraboutwhentouseit.Theansweristouseio.open()instead.It'slikeifIask"whenshouldIuseawrenchtodriveanailintoawall?".Therightansweris"useahammer".
– Bdoserror
Apr5,2017at17:47
Addacomment
|
22
Personally,Ialwaysusecodecs.openunlessthere'saclearidentifiedneedtouseopen**.Thereasonisthatthere'sbeensomanytimeswhenI'vebeenbittenbyhavingutf-8inputsneakintomyprograms."Oh,Ijustknowit'llalwaysbeascii"tendstobeanassumptionthatgetsbrokenoften.
Assuming'utf-8'asthedefaultencodingtendstobeasaferdefaultchoiceinmyexperience,sinceASCIIcanbetreatedasUTF-8,buttheconverseisnottrue.AndinthosecaseswhenItrulydoknowthattheinputisASCII,thenIstilldocodecs.openasI'mafirmbelieverin"explicitisbetterthanimplicit".
**-inPython2.x,asthecommentonthequestionstatesinPython3openreplacescodecs.open
Share
Follow
answeredNov1,2012at16:14
AdamParkinAdamParkin
17k1616goldbadges6565silverbadges8686bronzebadges
3
1
whatIdon'treallygetiswhyopensometimescanhandleverywelltheUTF-8encodednon-latincharactersoftheunicodeset,andsometimesitfailsmiserabily...
– cedbeu
Mar27,2013at18:45
Thismakessensetome.io.opendoesnottakeanencodingparamfromwhatIcanseeinpython2.7.5
– radtek
Jan23,2018at15:52
4
@radtek,youarerightthatthisisundocumented;however(atleastin2.7.12)io.openacceptsencodingandnewlineparametersandinterpretsthemasPython3does.Unlikecodecs.open,afileopenedwithio.openwillraiseTypeError:write()argument1mustbeunicode,notstreveninPython2.7ifyouattempttowritestr(bytes)toit.Afileopenedwithcodecs.openwillinsteadattemptimplicitconversiontounicode,oftenleadingtoconfusingUnicodeDecodeErrors.
– jochietoch
Sep2,2018at7:49
Addacomment
|
10
InPython2thereareunicodestringsandbytestrings.Ifyoujustusebytestrings,youcanread/writetoafileopenedwithopen()justfine.Afterall,thestringsarejustbytes.
Theproblemcomeswhen,say,youhaveaunicodestringandyoudothefollowing:
>>>example=u'ΜουαρέσειΕλληνικά'
>>>open('sample.txt','w').write(example)
Traceback(mostrecentcalllast):
File"
延伸文章資訊
- 1List of open-source codecs - Wikipedia
Video codecsEdit · OpenVVC an VVC /H. · x265 – An encoder based on the High Efficiency Video Codi...
- 2Difference between open and codecs.open in Python
open accepts encoding and newline parameters and interprets them as Python 3 does. Unlike codecs....
- 3Python小坑:open()和codecs.open()区别,以及常见指令和 ...
啥也别说了,用codecs.open()就完事了写贴原因因为接触Python时候已经是Python3.x的年代了,用的文件操作最多的就是with open() as file_:这一段话, ...
- 4Python codecs.open方法代碼示例- 純淨天空
本文整理匯總了Python中codecs.open方法的典型用法代碼示例。如果您正苦於以下問題:Python codecs.open方法的具體用法?Python codecs.open怎麽用?
- 5codecs — Codec registry and base classes — Python 3.10.7 ...
This module defines base classes for standard Python codecs (encoders and decoders) ... codecs. o...