0

I'm new to python (learning for 2 weeks only) and there's something I really can't even try (I have been googling for an hour and coulndn't find any).

file1 and file2 are both CSV files.

I've got a function that looks like:

def save(file1, file2): 

it is for file2 to have the same content as file1. For example, when I do:

save(file1, file2)

file2 should have the same content as file1.

Thanks in advance and sorry for an empty code. Any help would be appreciated!

Mat
  • 202,337
  • 40
  • 393
  • 406
John
  • 1
  • 2
    Are you supposed to first *read* the file and *then* write it out again? If not, you may want to explore the [shutil](http://docs.python.org/library/shutil.html) module and look for copy type operations. – Levon Aug 21 '12 at 12:25
  • possible duplicate of [How do I copy a file in python?](http://stackoverflow.com/questions/123198/how-do-i-copy-a-file-in-python) – hochl Aug 21 '12 at 12:51

2 Answers2

3

Python has a standard module shutil which is useful for these sorts of things.

If you need to write the code to do it yourself, simply open two files (the input and the output). Loop over the file object, Reading lines from the input file and write them into the output file.

Abbas
  • 3,872
  • 6
  • 36
  • 63
mgilson
  • 300,191
  • 65
  • 633
  • 696
  • You're so fast. I don't know why I even try, ha – chucksmash Aug 21 '12 at 12:28
  • 1
    I know it's just something weird with how stackoverflow estimates or updates times but right now it says john asked this question 25 seconds ago and that you answered it 1 minute ago. Jon Skeet, is that you? – chucksmash Aug 21 '12 at 12:29
  • @IamChuckB -- You caught me. I'm really Jon Skeet gaming the system to increase my already rediculous reputation. Also I answered the question before it was asked because I can do that sort of thing (I am Jon Skeet after all :-p) – mgilson Aug 21 '12 at 12:35
1

If you simply want to copy a file you can do this:

def save(file1, file2):
    with open(file1, 'rb') as infile:
        with open(file2, 'wb') as outfile:
            outfile.write(infile.read())

this copies the file with name file1 to the file with name file2. It really doesn't matter what the content of those files is.

hochl
  • 12,524
  • 10
  • 53
  • 87
  • It matters if `file1` is 10Gb in size. :) – mgilson Aug 21 '12 at 12:44
  • Yeah, in this case you have to replace the `read`/`write` call with a loop and only read segments. But for a homework implementation this should do the job :) – hochl Aug 21 '12 at 12:45
  • Which brings up another good point -- on a homework question, do you really want to give the answer outright like this? – mgilson Aug 21 '12 at 12:47
  • Actually if he's been googling for one hour he might never find the solution himself :( I typed in `python copy file howto` and the first hit with Google is http://stackoverflow.com/q/123198/589206 :) Maybe I should mark this question as a duplicate? – hochl Aug 21 '12 at 12:48