File corrupts while trying to copy it

Asked

Viewed 30 times

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"
  • You can post the code directly to the question. The site has support for such.

  • tried using the tag code but got messy along with the rest of the question

  • If you want to put the code in the question copy and paste then have a button in the question edition that allows you to ident the code...

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, read all the content with fl.read() and runs byte by byte by performing the rstrip() in each byte. That doesn’t even make sense anymore. Why run byte to byte of the file and yet run a rstrip in it?

And when you do:

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

You will write only the last byte of the read file, 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)
  • perfect, thanks for the help, I used rstrip() to remove n, I will use this for network transfer, then the shutil will not help me... thanks friend!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.