#encoding: Utf-8 Import Os,sys Import Shutil From Shutil import Error From Shutil import Copystat From Shutil import copy2 def copy_file (Src_file, Dst_dir): #声明函数 copy_file (Files to be copied, target directories, copy symbols to a new directory, no files to ignore)
"Copy the contents of a file so that it is in another directory." If Os.path.isfile (src_file): If Os.path.isdir (dst_dir): #dst目标存在时, on pass, does not exist on the Create Pass Else Os.makedirs (Dst_dir)
Errors = [] #声明 errors Column Print Src_file SrcName = Src_file filename = Os.path.basename (src_file) DstName = Os.path.join (dst_dir, filename) #将路径名 (DST) is added before Wennan (name) and then assigned to Dstcname From Shutil import Error Try: #尝试 If Os.path.isfile (srcname): #如果srcname文件是存在 Copy2 (SrcName, DstName) Print Srcname,dstname, ' success ' Elif Os.path.isdir (dstname): #目标文件存在, delete, and then copy the new Os.remove (DstName) print ' remove%s '% DstName Copy2 (SrcName, DstName)
Except (IOError, Os.error), Why: #除 (ioerror[file-related exceptions], operating system exceptions), return reason Errors.append ((SrcName, DstName, str (why)) # Add to Errors column (directory to replicate, destination directory, error reason) # Catch the error from the ' recursive jiecptree so we can capture this bug from recursive replication so we could continue to copy other files # Continue with other files Except error, err: #除错误外, returning errors: Errors.extend (err.args[0]) #扩展 errors column, adding (err.args[0] Element)
Try: #尝试 Copystat (SrcName, DstName) # copies its permission bits from the file represented by SrcName, last access time, last modified time to DST, Except Windowserror: # In addition to Windows errors: # can ' t copy file access time on Windows cannot copy files on Windows Pass # through (without any processing) Except OSError, why: # reason to return except operating system error: Errors.extend ((Src_file, Dst_dir, str (why)) #扩展 errors column, add (file to copy, target directory, error reason) If errors: # if the error Raise error (Errors) # Prompts for errors Else print ' The fisrt parm should be a file name '
if __name__ = = ' __main__ ': If Len (SYS.ARGV)!= 3: print ' Need srcfile and Dstdir ' Sys.exit (-1) Srcfile = sys.argv[1] Dstdir = sys.argv[2] Copy_file (Srcfile, Dstdir) |