How to write a check in python to see if file is ... - Exchangetuts

文章推薦指數: 80 %
投票人數:10人

As stated in title, I would like to check in given file object (opened as binary stream) is valid UTF-8 file. Anyone? Thanks. like image 682. Jox Avatar ... Questions Linux Laravel Mysql Ubuntu Git Menu HTML CSS JAVASCRIPT SQL PYTHON PHP BOOTSTRAP JAVA JQUERY R React Kotlin × Linux Laravel Mysql Ubuntu Git   HowtowriteacheckinpythontoseeiffileisvalidUTF-8? Tags: Asstatedintitle,Iwouldliketocheckingivenfileobject(openedasbinarystream)isvalidUTF-8file. Anyone? Thanks 682 askedJul17'1005:07 Jox Peoplealsoask HowdoIcheckifafileisUTF-8encodedinPython? Couldbesimplerbyusingonlyoneline:codecs.open("path/to/file",encoding="utf-8",errors="strict"). HowcanItellifafileisUTF-8? Toverifyifafilepassesanencodingsuchasascii,iso-8859-1,utf-8orwhateverthenagoodsolutionistousethe'iconv'command. HowdoIknowifmyfileisUTF16orUTF-8? Thereareafewoptionsyoucanuse:checkthecontent-typetoseeifitincludesacharsetparameterwhichwouldindicatetheencoding(e.g.Content-Type:text/plain;charset=utf-16);checkiftheuploadeddatahasaBOM(thefirstfewbytesinthefile,whichwouldmaptotheunicodecharacterU+FEFF-2bytesfor... HowdoyouwritetoatextfilewithUTF-8inPython? Usewrite()andwritelines()methodstowritetoatextfile.Passtheencoding='utf-8'totheopen()functiontowriteUTF-8charactersintoafile. 2Answers deftry_utf8(data): "ReturnsaUnicodeobjectonsuccess,orNoneonfailure" try: returndata.decode('utf-8') exceptUnicodeDecodeError: returnNone data=f.read() udata=try_utf8(data) ifudataisNone: #NotUTF-8.Dosomethingelse else: #Handleunicodedata 113 answeredSep19'2220:09 DanielStutzbach Youcoulddosomethinglike importcodecs try: f=codecs.open(filename,encoding='utf-8',errors='strict') forlineinf: pass print"Validutf-8" exceptUnicodeDecodeError: print"invalidutf-8" 38 answeredSep21'2220:09 michael Signinto Comment Relatedquestions HowdoIaccesstheHTTPHeaderofrequestinaCGIscript? HowcanIdeletealltherecordsfromaTClientDatasetatonce? WPFcustomcommandincontextmenuaredisableduntilanybuttonclicked AvoidorembraceC#constructswhichbreakedit-and-continue? Mysql-findatableinalldatabase Minimumwindowwidthinstringxthatcontainsallcharactersofstringy WhyareCPUregistersfasttoaccess? MySQLwithSoft-Deletion,UniqueKeyandForeignKeyConstraints Howtoprogrammaticallycreatebeandefinitionwithinjectedproperties? IsBizTalkanESB? DataGridViewboundtoBindingListdoesnotrefreshwhenvaluechanged Howtosaveuser.configtoAppData\RoamingfolderinsteadofAppData\Local? RecentActivity Howcanwewritemaven2plugininScala? SwitchshaderprograminWebGL Howtoaccess"Activity.this"inKotlin? CanIusemyoldc#-librarieswithWinJS? Handlingclickableareasinimageview Whycan'tIsetaQObjectparentinaclassofwhichQObjectisonlyanindirectbase? DonateForUs Ifyouloveus?YoucandonatetousviaPaypalorbuymeacoffee sowecanmaintainandgrow!Thankyou!



請為這篇文章評分?