File corrupts when trying to copy it [closed]

0

I was trying to copy a file using Python, but the file corrupts ... Look at the code:

#!/usr/bin/env python
cf = raw_input("File: ")
ds = raw_input("Destino: ")
with open(cf,"rb") as fl:
  for l in fl.read():
    l.rstrip()
with open(ds,"wb") as rw:
  rw.write(l)
print "OK"
    
asked by anonymous 16.08.2018 / 17:08

1 answer

0

You did:

with open(cf,"rb") as fl:
  for l in fl.read():
    l.rstrip()

That is, open the file for binary reading, reads all content with fl.read() and traverses byte to byte by doing rstrip() on each byte. That does not even make sense. Why go through byte byte of the file and still execute a rstrip on it?

And when you do:

with open(ds,"wb") as rw:
  rw.write(l)

You will only write the last byte of the file read, which will not be a valid file - indicating that it is corrupted.

What you need to do is:

with open(cf, 'rb') as entrada:
    with open(ds, 'wb') as saida:
        saida.write(entrada.read())

Or even (Python 2.7 +):

with open(cf, 'rb') as entrada, open(ds, 'wb') as saida:
    saida.write(entrada.read())

But why reinvent the wheel? Use shutil.copyfile :

from shutil import copyfile

copyfile(cf, ds)
    
16.08.2018 / 17:54