tags:

views:

51

answers:

2

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.

+3  A: 

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')

Nathon
I always wondered what on earth the binary bit did - I've used it and not used it and could never tell a difference. And now I know.
Wayne Werner
OMG! That f***ing binary flag! Damn Win32 :) and shame on me!
Cristiano Paris
A: 

I always use system processes, here's the quick and dirty way

import os, subprocess
cmd='move filename1 filename2'
p = subprocess.Popen(['/bin/bash', '-c',cmd],stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
p.stdout.read()

I'm afraid I've completely forgotten what you have to change '/bin/bash' to in windows, I assume it's something like C:\Windows\cmd.exe?

EricR
That is not portable and would not work under Windows.
Fabian
Thank you. I was unaware of that.
EricR
Even in a *nix environment, this is dangerous. Unless you sanitize the names you're passing in for `filename1` and `filename2`, you could be inviting malicious code to execute with the subprocess' privileges.
eksortso
There was no indication that this was from user input and there was a possibility of malicious code, whenever I use this code, it's always hardcoded.
EricR