1, how to judge how to read the file is GBK or utf-8 encoded if content = = U ' China '. Encode (' GBK '): return ' GBK ' elif content = = U ' China '. Encode (' Utf-8 '): return ' utf-8 ' 2, if not os.path.exists (FilePath): Os.mkdir (FilePath) determine if the directory exists, It doesn't exist. Create if Os.path.exists (Dirpath): for root,dirs,files in Os.walk (dirpath): Determine if the path exists before traversing a directory 3 , using the system command Copy file Os.system (' Copy e:\\tmp\\t23.txt e:\\tmp\\t999.txt ') 4, file operations, For all possible scenarios such as path processing the input source file is located in the path and destination directory path, and then the file copy function # Encoding=utf-8import OS for the source directory and the target directory all possible scenarios did the exception processing def copy (RESF, DESF): RESF = Os.path.normpath (RESF) DESF = Os.path.normpath (DESF) if not os.path.exists ( RESF): print ' File not exists ' return false elif RESF = = desf: print ' DESF error ' return false elif Os.path.ex Ists (DESF): while true: print U ' overwrite%s? (y/n) '%desf, Inputvar = Raw_input (). Lower () if Inputvar = = ' n ':   ; print U ' file already exists, copy 0 files ' return false  ; elif Inputvar = = ' Y ': os.remove (DESF) &NBS P break else: continue with open (RESF As fp: content = Fp.read () with open (DESF, ' W ') as fp: Fp.write (content) Print U ' copied 1 files ' return true if __name__ = = ' __main__ ': cop Y (' e:\\tmp\\t23.txt ', ' e:\\tmp\\t1234.txt ') 5, when the format of a file is more but can be enumerated, you can enumerate it all in the list to traverse a directory of all the pictures, and after the image name added _ Xxpicends = ['. jpg ', '. jpeg ', '. BPM ', '. png ', '. gif ']
Python file operations: Experience summary