Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying files with Python under Windows

Tags:

python

I'm trying to copy files inside a Python script using the following code:

inf,outf = open(ifn,"r"), open(ofn,"w")
outf.write(inf.read())
inf.close()
outf.close()

This works perfectly unedr OSX (and other UNIX flavors I suspect) but fails under Windows. Basically, the read() call returns far less bytes than the actual file size (which are around 10KB in length) hence causing the write truncate the output file.

The description of the read() method says that "If the size argument is negative or omitted, read all data until EOF is reached" so I expect the above code to work under any environment, having Python shielding my code from OSs quirks.

So, what's the point? Now, I resorted to shutil.copyfile, which suits my need, and it works. I'm using Python 2.6.5

Thank you all.

like image 306
Cristiano Paris Avatar asked Jul 15 '10 16:07

Cristiano Paris


People also ask

How do I copy a file to another file in Python?

The shutil. copy() method in Python is used to copy the content of the source file to destination file or directory.

Does Shutil work on Windows?

It means you should know the target OS (Windows/Linux/Mac OS X etc.) wherever you'll run the program. With the shutil module, you can automate copying both the files and folders. This module follows an optimized design.


1 Answers

shutil is a better way to copy files anyway, but you need to open binary files in binary mode on Windows. It matters there. open(fname, 'rb')

like image 66
nmichaels Avatar answered Oct 26 '22 14:10

nmichaels