Python implements a batch conversion method from ANSI to UTF-8 Java source code

Source: Internet
Author: User
This article describes a Python-based batch conversion method that implements Java source code from ANSI to UTF-8. Share to everyone for your reference. Specific as follows:

Like with eclipse of the great gods, may accidentally code becomes ANSI code, need to convert to Utf-8, a file of a file in the Notepad2 or notepad++ inside conversion? No, there are batch conversion programs, Python implementation, need to take to use it.

ansi2utf8.py:

#-*-coding:utf-8-*-import codecsimport osimport shutilimport reimport chardetdef convert_encoding (filename, target_ encoding): # Backup the origin file. Shutil.copyfile (filename, filename + '. Bak ') # Convert file from the source encoding to target encoding content = CODECS.O Pen (filename, ' r '). Read () source_encoding = chardet.detect (content) [' Encoding '] print source_encoding, filename Content = Content.decode (source_encoding) #.encode (source_encoding) codecs.open (filename, ' W ', encoding=target_ encoding). Write (content) def main (): for root, dirs, files in Os.walk (OS.GETCWD ()): For F in Files:if F.lower (). Endswit     H ('. Java '): filename = Os.path.join (root, f) try:convert_encoding (filename, ' utf-8 ') except Exception, E:   Print Filenamedef process_bak_files (action= ' Restore '): For root, dirs, files in Os.walk (OS.GETCWD ()): For F in Files: If F.lower (). EndsWith ('. Java.bak '): Source = Os.path.join (root, f) target = Os.path.join (root, Re.sub (' \.java\.bak$ ', '. Java ',F, Flags=re. IGNORECASE)) try:if action = = ' restore ': shutil.move (source, target) elif action = = ' Clear ': Os.remo ve (source) except Exception, e:print sourceif __name__ = = ' __main__ ': # process_bak_files (action= ' Clear ') main ()

It's good to copy the program to the directory where the Java source files are located.

Hopefully this article will help you with Python programming.

  • Related Article

    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.