Hrvoje T
Hrvoje T

Reputation: 3913

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?

Upvotes: 2

Views: 373

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140148

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)

Upvotes: 2

Related Questions