Hrvoje T Hrvoje T - 1 year ago 95
Python Question

Trying to get progress from copyfileobj in Python

from threading import Thread

src_file = 'test.txt'
dst_file = 'test_copy.txt'

def cb(file_size):
print("Copied: {}\n".format(file_size))

def copyfileobj(fsrc, fdst, callback, length=8*1024):
copied = 0
while True:
buff = fsrc.read(length)
if not buff:
break
fdst.write(buff)
copied += len(buff)
callback(copied)

t = Thread(target=copyfileobj, args=[src_file, dst_file, cb]).start()


When I run this I get:


buf = fsrc.read(length) AttributeError: 'str' object has no attribute
'read'


How should I make that
fsrc
has read attribute?

Answer Source

you're mixing up file name and file handle.

You have to open the files using the filename to get the file handle, for both reading & writing.

def copyfileobj(fsrc, fdst, callback, length=8*1024):
    copied = 0
    with open(fsrc,"rb") as fr, open(fdst,"wb") as fw:
      while True:
        buff = fr.read(length)
        if not buff:
            break
        fw.write(buff)
        copied += len(buff)
        callback(copied)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download