Notepad++ convert to UTF-8 multiple files - Stack Overflow
文章推薦指數: 80 %
Need to batch convert a large quantity of text files from ANSI ... 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 Notepad++converttoUTF-8multiplefiles AskQuestion Asked 6years,7monthsago Modified 2monthsago Viewed 20ktimes 14 Thefunction"ConverttoUTF-8withoutBOM"ofNotepad++isreallynice.ButIhave200filesandallofthemneedtobecoverted.ThereforIfoundthislittlepythonscript: importos; importsys; filePathSrc="C:\\Temp\\UTF8" forroot,dirs,filesinos.walk(filePathSrc): forfninfiles: iffn[-4:]!='.jar'andfn[-5:]!='.ear'andfn[-4:]!='.gif'andfn[-4:]!='.jpg'andfn[-5:]!='.jpeg'andfn[-4:]!='.xls'andfn[-4:]!='.GIF'andfn[-4:]!='.JPG'andfn[-5:]!='.JPEG'andfn[-4:]!='.XLS'andfn[-4:]!='.PNG'andfn[-4:]!='.png'andfn[-4:]!='.cab'andfn[-4:]!='.CAB'andfn[-4:]!='.ico': notepad.open(root+"\\"+fn) console.write(root+"\\"+fn+"\r\n") notepad.runMenuCommand("Encoding","ConverttoUTF-8withoutBOM") notepad.save() notepad.close() Itgoesthrougheveryfile->Icanseethis.Butafteritfinished,thecharsetisstilANSIinmycase:/ Cananyonehelpme? pythonutf-8consolenotepad++ Share Follow askedFeb20,2016at17:17 PhilPhil 89322goldbadges66silverbadges1818bronzebadges 2 1 Arethereanyerrormessages?Yourunthisintothe"notepad++PythonScriptplugin"?Maybeyoucancheckiftherereallyisa"ConverttoUTF-8withoutBOM"intheEncodingmenu.Inmynotepad++thereisonlya"ConverttoUTF-8".Itcouldbeworthchangingthestring. – LarsFischer Feb20,2016at17:33 Right,Iusethisplugin.Andinmynotepadthereis"ConverttoUTF-8withoutBOM"and"CoverttoUTF-8"-soboth. – Phil Feb20,2016at17:40 Addacomment | 4Answers 4 Sortedby: Resettodefault Highestscore(default) Trending(recentvotescountmore) Datemodified(newestfirst) Datecreated(oldestfirst) 18 Hereiswhatworkedforme: GotoNotepad++->Plugins->PluginsAdmin. FindandinstallPythonScriptplugin. CreatenewpythonscriptwithPlugins->PythonScript->Newscript. Insertthiscodeintoyourscript: importos; importsys; filePathSrc="C:\\Users\\YourUsername\\Desktop\\txtFolder" forroot,dirs,filesinos.walk(filePathSrc): forfninfiles: iffn[-4:]=='.txt'orfn[-4:]=='.csv': notepad.open(root+"\\"+fn) console.write(root+"\\"+fn+"\r\n") notepad.runMenuCommand("Encoding","ConverttoUTF-8") notepad.save() notepad.close() ReplaceC:\\Users\\YourUsername\\Desktop\\txtFolderwithpathtoyourWindowsfolderwhereyourfilesare. Scriptworkswith.txtand.csvfilesandignoresallotherfilesinfolder. RunscriptwithPlugins->PythonScripts->Scripts->nameofyourscript Share Follow editedJun17,2020at7:26 answeredMay28,2020at1:55 HrvojeHrvoje 11.4k66goldbadges7272silverbadges8888bronzebadges 5 Areyousurethesecondconditionfn[-5:]iscorrect?Ibelieveitshouldbefn[-4:]too,because.csvisthesamelengthas.txt.BesidesIwouldrecommendtousetheendswithmethodifpossible. – turbolocust Jun15,2020at17:39 @turbolocustrightyouaremyfriend.changedaccordingly. – Hrvoje Jun17,2020at7:34 1 ThisdeservesanupvoteasItriedmultiplethingsonwindowsandthisistheonlyonethatactuallyworked.Thankyou – tim Jul13,2021at16:11 Ihadproblemswithsomeofthefileshavingnon-asciicharactersintheirname.SoIhadtochange"opening"partofthescript.filePath=os.path.join(root,fn).decode(sys.getfilesystemencoding()).encode('utf8')notepad.open(filePath)console.write(filePath+"\r\n")OtherwiseNotepad++promotedmetosavefileasanewcopywithmessedupfilenameforfilenamescontainingnon-asciicharacters. – Almighty May16at7:32 Source:gist.github.com/bjverde/a6e822c91b0826ce05930f0f9aaec61c – mesompi 18hoursago Addacomment | 7 Gotmymistake.Mynotepadisingerman.Sotakecareifit'scalled"Encoding"orinmycase"Kodierung"and"ConverttoUTF-8withoutBOM"is"KonvertierezuUTF-8ohneBOM" Thathelpedmeout! Share Follow answeredFeb20,2016at17:43 PhilPhil 89322goldbadges66silverbadges1818bronzebadges 0 Addacomment | 2 Youalsocanrecordandplaybackamacrohere.Tthat'swhatworkedformesincethePlugInmanagerissomehowbrokenIdon'thavePythonavailable. dragasetoffiles(orall-Ithinkthereisalimitinthemaximumnumberoffiles)intonotepad++ Macro->Startrecording dotheconversion savefile closefile Macro->Stoprecording Youcanplaybackthemacrobyselecting Macro->RunaMacroMultipleTimes Enteravaluesuchthatallfilesareprocessed Sincethefilesareclosedafterprocessing,youwillknowwhichfileshavenotbeenprocessedyet. Share Follow answeredNov19,2021at12:49 klausklaus 2111bronzebadge 1 Thisisit!Muchsimplerthanfiddlingwithsomepythonscript. – ArminBu Jul26at16:33 Addacomment | 0 USENOTEPAD++PythonSCriptPlugin.CopythiscodeintoaNEWSCRIPT: #-*-coding:utf-8-*- from__future__importprint_function fromNppimportnotepad importos uft8_bom=bytearray(b'\xEF\xBB\xBF') top_level_dir=notepad.prompt('Pastepathtotop-levelfoldertoprocess:','','') iftop_level_dir!=Noneandlen(top_level_dir)>0: ifnotos.path.isdir(top_level_dir): print('badinputfortop-levelfolder') else: for(root,dirs,files)inos.walk(top_level_dir): forfileinfiles: full_path=os.path.join(root,file) print(full_path) withopen(full_path,'rb')asf:data=f.read() iflen(data)>0: iford(data[0])!=uft8_bom[0]: try: withopen(full_path,'wb')asf:f.write(uft8_bom+data) print('addedBOM:',full_path) exceptIOError: print("can'tchange-probablyread-only?:",full_path) else: print('alreadyhasBOM:',full_path) SECONDSOLUTIONISTOUSEREGEX,findandreplace: Findinfiles: SEARCH:\A REPLACEBY:\x{FEFF}FILTERS*.html(youhavetogiveOkfromthefirst,don'tcancel) Share Follow answeredAug1at14:27 JustMeJustMe 67322goldbadges1414silverbadges2727bronzebadges Addacomment | YourAnswer ThanksforcontributingananswertoStackOverflow!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers. Draftsaved Draftdiscarded Signuporlogin SignupusingGoogle SignupusingFacebook SignupusingEmailandPassword Submit Postasaguest Name Email Required,butnevershown PostYourAnswer Discard Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy Nottheansweryou'relookingfor?Browseotherquestionstaggedpythonutf-8consolenotepad++oraskyourownquestion. TheOverflowBlog HowtoearnamillionreputationonStackOverflow:beofservicetoothers Therightwaytojobhop(Ep.495) FeaturedonMeta BookmarkshaveevolvedintoSaves Inboximprovements:markingnotificationsasread/unread,andafiltered... Revieweroverboard!Orarequesttoimprovetheonboardingguidancefornew... CollectivesUpdate:RecognizedMembers,Articles,andGitLab Shouldweburninatethe[script]tag? Linked 0 CheckingoutfromGitaswindows-1252,butcommitingasUTF-8?Isthisevenagoodpractice? 1 problemsfirstrowxml Related 3430 Howtocopyfiles? 1322 UTF-8allthewaythrough 1228 ConverttabstospacesinNotepad++ 2851 Convertstring"Jun120051:33PM"intodatetime 3469 Convertbytestoastring 1239 HowtoreformatJSONinNotepad++? 3467 HowdoIlistallfilesofadirectory? 1987 HowdoIformatXMLinNotepad++? 2239 Importingfilesfromdifferentfolder 3585 Catchmultipleexceptionsinoneline(exceptblock) HotNetworkQuestions HowdothosewhoholdtoaliteralinterpretationofthefloodaccountrespondtothecriticismthatNoahbuildingthearkwouldbeunfeasible? StrangeFruitfromTomatoPlant Whenisthefirstelementintheargumentlistregardedasafunctionsymbolandwhennot? DotheseresultsmeanthatIhavefoundthisexoplanet? Whataretheargumentsforrevengeandretribution? Howcanmyaliensymbiotesidentifyeachother? Whattranslation/versionoftheBiblewouldChaucerhaveread? WhattestamItaking,anyways‽ Howdoparty-listsystemsaccommodateindependentcandidates? Doyoupayforthebreakfastinadvance? Howtosimplifyapurefunction? Botchingcrosswindlandings ElectronicCircuitsforSafeInitiationofPyrotechnics? AmIreallyrequiredtosetupanInheritedIRA? Areopeningandclosingstatementspartoftherecord? SearchApplicationLogforstringbasedontimeframewithPowerShell Isitokaytore-renderaplotusedinanotherpublication? Howtoelegantlyimplementthisoneusefulobject-orientedfeatureinMathematica? Interpretinganegativeself-evaluationofahighperformer ConvertanintegertoIEEE754float WhathappenswhenthequasarremnantsreachEarthin3millionyears? ArethereanyspellsotherthanWishthatcanlocateanobjectthroughleadshielding? HowdoGPSreceiverscommunicatewithsatellites? Canaphotonturnaprotonintoaneutron? morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-py Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings
延伸文章資訊
- 1convert2utf - PyPI
***Batch mode***: Pass in a directory as the input, and all text files that meets the criteria un...
- 2Convert multiple files to UTF-8 encoding with Notepad++
This file will search all files and folders within a given directory, and use Notepad++ to conver...
- 3How To Batch Convert Text Files To UTF-8 Encoding
UTFCast is a small tool for Windows that lets you batch convert all text files to UTF-8 encoding....
- 4Batch convert encoding in files - Super User
UTFCast is a Unicode converter that lets you batch convert all text files to UTF encodings with j...
- 5How do you batch convert UTF-16 to UTF-8? - PTC Community
So, I have attempted to create a Windows Command Line batch file to open Arbortext Editor and exe...