Python solves JS file Utf-8 encoding garbled problem

Source: Internet
Author: User
This article mainly introduces the Python to solve JS file Utf-8 encoding garbled problem, very good, with reference value, the need for friends can refer to the next

HTML file introduced JS file, display garbled!

JS file for Utf-8 encoding (no BOM), at this time as long as the JS file into the Utf-8 BOM code can be solved

can use notepad++ transcoding

You can also use the following Python code to bulk transcode

#-*-coding:utf-8-*-import os,sys import chardet def convert (filename, In_enc = "GBK", out_enc= "UTF-8"): Try:p Rint ("convert" + filename) F = open (filename, ' rb ') content = f.read () result = chardet.detect (content) #通过char     Det.detect Gets the encoding format string for the current file, the return type is dictionary type print (result) f.close () coding = result.get (' encoding ') #获取encoding的值 [encoded format]       If coding! = ' Utf-8-sig ' and coding = = ' Utf-8 ': #文件格式如果是utf-8 when the transcoding print (coding + "to" + Out_enc + "!") New_content = Content.decode (In_enc). Encode (Out_enc) f = open (filename, ' WB ') F.write (new_content) F.clo   SE () print ("Done") else:print (coding) except IOError as E: # Except:print (E) def explore (dir): For root, dirs, files in Os.walk (dir): for file in Files:path = Os.path.join (root, file) convert (path) def main (dir): if (Os.path.isdir (dir)): Fpaths = [Fpath for Fpath in Os.listdir (dir) if Os.path.isfile (dir+ "\ \" +fpath ) and Fpath.endswith ('. js')] dpaths = [Dpath for Dpath in Os.listdir (dir) if Os.path.isdir (dir+ "\ \" +dpath)] for F in Fpaths:convert ( dir+ "\ \" +f, ' utf-8 ', ' Utf-8-sig ') for D in Dpaths:print (d) Main (dir+ "\ \" +d) if __name__ = "__main__": MA In (' directory ')

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.