Python easily implements code encoding format conversion _python

Source: Internet
Author: User

Recently just changed jobs, not much time to clean up the things in the work, most of the time is used to familiarize themselves with the business of the new company, familiar with their code framework, the most important thing is that there are a lot of new things to learn, I was mainly doing PHP backstage development, come here and then I halfway decent to learn the front end, but also to learn c+ +, Haha, in short, very substantial, every day after work home can sleep very fragrant (a sentence summary, is to eat incense, sleep incense ~). Say again to change work time, the beginning of this year officially graduated six months, feel oneself technology grows very quickly, the original company inside the position of the programmer is inferior to operate, so want to change a job, interview 3 (2 big, a small one), all give an offer, of course from big company inside pick a all aspect synthesis (salary, do, Traffic and so on) is also good, anyway feel very smooth came in (more than the time of graduation is much easier), haha, the more efforts, the more fortunate, the more fortunate, the more efforts! From this week onwards, continue to organize your blog, lest you create lazy habits.

Just came to this company, familiar with the environment, boss began to let me do a migration, modify the code work, I want to say is that this kind of work is really boring ~ ~, look at other people's code, to change the code, here to change a variable, where to change the filename, there are no technical content, very cumbersome things, But by migrating code, you know the environment. So much to talk about today's topic-code format changes, for some reason, need to move the code from a computer room to B room, the two can not access each other, but the historical reasons cause a computer room code is all UTF8 coding, B room requirements is GBK code, see how this solves.

Coding problems
first say why there are coding problems, take the above example, B computer room on this side of the database are all GBK encoded, so the data taken from the database are GBK, from the database out of the data is GBK code, to show the time is not garbled, In the case where the data is not converted from the database, it is necessary to set the encoding to GBK when the header is sent, and the output file (HTML, TPL, etc.) must be GBK to see that the following diagram will be clearer:

DB (GBK) => PHP (encoding format is not limited but if there are Chinese characters in the code file, the file will be GBK encoded or converted to GBK when the Chinese character is exported) => header (GBK) => html, TPL (GBK)

Or there is a way to only when the library in the code in the UTF8 into the GBK, in general utf8 or more popular point, less problem

DB (GBK) => php (UTF8, and convert data removed from database to UTF8) => header (UTF8) => html, TPL (UTF8)

As long as the above two kinds of standard coding format, there will be no garbled situation, at least I test the first way is no problem, so I guess the second is OK, OK, now to write a conversion file encoding format of the small script:

#!/usr/bin/python #-*-Coding:utf-8-*-#Filename: changeencode.py import os import sys def changeencode (file,fromencod
    E,toencode): Try:f=open (file) s=f.read () f.close () U=s.decode Fromencode (S=u.encode)
    F=open (File, "w");
  F.write (s) return 0;

except:return-1; def do (Dirname,fromencode,toencode): For Root,dirs,files in Os.walk (dirname): For _file in Files: _file=os.pat
        H.join (Root,_file) if (Changeencode (_file,fromencode,toencode)!=0): Print [conversion failed:] ' +_file else: Print [success:] "+_file def checkparam (dirname,fromencode,toencode): encode=[" UTF-8 "," GBK "," GBK "," Utf-8 "] if (not Fromenc Ode in encode or not toencode in encode): Return 2 if (Fromencode==toencode): Return 3 if (not Os.path.isdir (dir Name): Return 1 return 0 if __name__== "__main__": Error={1: "The first parameter is not a valid folder", 3: "Source encoding and target encoding are the same", 2: "The encoding you want to convert is no longer in range: UTF -8,GBK "} dirname=sys.argv[1] fromencode=sys.argv[2] toencode=sys.arGV[3] Ret=checkparam (Dirname,fromencode,toencode) if (ret!=0): Print Error[ret] Else:do (dirname,fromencode,t

 Oencode)

The script is simple, and it's easy to use.

Copy Code code as follows:

./changeencode.py Target_dir Fromencode Toencode

Here's a note of the relationships of several common encodings:

The US-ASCII encoding is a subset of the UTF-8 encoding, which is obtained from the StackOverflow, which is the following: ASCII is a subset of UTF-8, so all ASCII files are already UTF-8 encoded ,

I tried it. Yes, when the characters are not added, the display code is US-ASCII, after adding the Chinese characters, it becomes utf-8.

There is the ASNI encoding format, which means that the local encoding format, for example, in the simplified Chinese operating system, ASNI encoding represents the GBK code, this also need to pay attention to

The other thing is that a command to view the file encoding format under Linux is:

Copy Code code as follows:

File-i *

You can see the encoding format of the file.

Of course, some of the above may have special characters in the file, the processing will fail, but the general program file is no problem.

The above is the entire content of this article, I hope to learn Python can help.

Please take a moment to share the article with your friends or leave a comment. We will sincerely thank you for your support!

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.