Python traverses the path file and converts it into UTF-8 encoding

Source: Internet
Author: User
The code is as follows Copy Code


Import Sys
Import string
Import OS

def detect_nowalk (Dir_path):
Files = Os.listdir (Dir_path)
For filename in Files:
Print "FILE:%SN"% filename
Next = Os.path.join (Dir_path, filename)
If Os.path.isdir (next):
Print "file folds:%sn"% filename
Detect_nowalk (Next)

if __name__ = = "__main__":
Detect_nowalk (".")
Import Sys
Import OS

def detect_walk (Dir_path):
For Root, dirs, the files in Os.walk (Dir_path):
For filename in Files:
Print "FILE:%SN"% filename
For dirname in dirs:
Print "DIR:%SN"% dirname

if __name__ = = "__main__":
Detect_walk (".") In addition, the use of the first method to convert file encoding source code, some files converted with Gedit Open is garbled, but with VI view is correct.


Import Sys
Import string
Import Codecs
Import OS
Import Shutil

def gbkToUtf8 (path):
Files = Os.listdir (path)
For filename in Files:
If Os.path.isdir (filename):
Print "file folds:%sn"% filename
GbkToUtf8 (filename)
Continue

Try
tokens = string.splitfields (filename, '. ')
If Len (tokens)!= 2 or tokens[1]!= ' txt ':
#print Tokens[1]
Continue
Else
print ' Encode converting (GBK to UTF-8): ', filename
Utffile=open (filename)
Tstr = Utffile.read ()
#tstr = Utffile.read (). Decode ("GBK") is wrong
Tstr = Tstr.encode ("UTF-8")
Utffile.close ()
Utffile = open (filename, ' W ')
Utffile.write (TSTR)
Utffile.close ()
Except
print ' Error%s '%filename

if __name__ = = "__main__":
GbkToUtf8 (".")

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.