#!/usr/bin/python#Coding:utf8ImportOSImportChardetImportSYSImportTracebackImportLogging#traversing FilesdefGet_all_file_path (Path, All_file_path):""":p Aram Path: The specified scan path:p aram All_file_path: Save the path to each file: return:""" if notOs.path.isdir (path):Print "%s The file path does not exist"%(PATH)return[] filelist=os.listdir (path) forFileNameinchFilelist:filepath=os.path.join (path, filename)#recursion: Determine if the file path is not a folder, and if you continue calling the function ifOs.path.isdir (filepath): Get_all_file_path (filepath, All_file_path)Else: All_file_path.append (filepath)returnAll_file_path#transcodingdefFile_encode (File_path, Final_file_name, Target_code):""":p Aram File_path: File name and path to convert:p Aram Final_file_name: Conversion of a successful file to the specified file: Return:boolean:target_code: Specified target Coding""" Try: #Read the fileFile_obj = open (File_path,'R') #Get file ContentsFile_content =File_obj.read ()#determine the encoding format of the file contentsFile_code =Chardet.detect (file_content)#decode and Transcode (must write decode to be able to transcode)Gbk_file_content = File_content.decode (file_code['encoding']). Encode (Target_code)
File_obj.close () with open (Final_file_name,'WB') as Fp:fp.write (gbk_file_content)returnTrueexceptException:traceback.print_exc ()returnFalse#Example: Converting to GBKif __name__=='__main__': if notOs.path.isdir ('Gbk_file_data'): Try: Os.mkdir ('Gbk_file_data') exceptException, E:Print "Can not create dir:", EifLen (sys.argv) = = 2: All_file_path= Get_all_file_path (sys.argv[1], []) Else: Logging.error ("Please input file path!") Exit (1) forFile_pathinchAll_file_path:ifFile_encode (File_path,'gbk_file_data/'+'Gbk_'+file_path.split ('/') [-1],"GBK"): Print "%s--transcoding Success"%(File_path)Else: Print "%s--transcoding failed"% (File_path)
Python iterates through all files in the specified file directory and transcode them