Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying files in python 2.7

Ok well i have another question. I implemented the error checking but for some reason it still isn't working. I still get a python error instead of the error i just wrote in the program.

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'
like image 276
Aegg Avatar asked Dec 26 '22 16:12

Aegg


2 Answers

check out the shutil module in standard library:

shutil.copyfile(src, dst)

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

like image 93
Corey Goldberg Avatar answered Jan 04 '23 21:01

Corey Goldberg


I would rather ask you to write your own:

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

OUTPUT:

Copy: SUCCESSFUL
like image 43
Siva Cn Avatar answered Jan 04 '23 21:01

Siva Cn