在python 2.7中复制文件

时间:2013-12-16 17:12:17

标签: python python-2.7

好吧,我有另一个问题。我实现了错误检查,但由于某种原因它仍然无法正常工作。我仍然得到一个python错误,而不是我刚刚在程序中写的错误。

Traceback (most recent call last):
  File "E:/python/copyfile.py", line 31, in <module>
    copyFile()
  File "E:/python/copyfile.py", line 8, in copyFile
    file1 = open(source,"r")
IOError: [Errno 2] No such file or directory: 'C:/Users/Public/asdf.txt'

2 个答案:

答案 0 :(得分:4)

查看标准库中的shutil模块:

shutil.copyfile(src, dst)

http://docs.python.org/2/library/shutil.html#shutil.copyfile

答案 1 :(得分:1)

我宁愿让你自己写一下:

import os
import hashlib

def md5ChkSum(_file):  # Calculates MD5 CheckSum
    with open(_file, 'rb') as fp:
        hash_obj = hashlib.md5()

        line = fp.readline()
        while line:
            hash_obj.update(line)
            line = fp.readline()
        return hash_obj.hexdigest()

def copier(_src, _dst):
    if not os.path.exists(_src):
        return False

    _src_fp = open(_src, "r")
    _dst_fp = open(_dst, "w")

    line = _src_fp.readline()
    while line:
        _dst_fp.write(line)
        line = _src_fp.readline()
    _src_fp.close()
    _dst_fp.close()

    if md5ChkSum(_src) == md5ChkSum(_dst):
        return "Copy: SUCCESSFUL"
    return "Copy: FAILED"

res = copier(r"/home/cnsiva/6.jpg", r"/home/cnsiva/6_copied.jpg")
if not res:
    print "FILE Does not Exists !!!"
else: print res

输出:

Copy: SUCCESSFUL