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!

2
  • 2
    Are you supposed to first read the file and then write it out again? If not, you may want to explore the shutil module and look for copy type operations. Commented Aug 21, 2012 at 12:25
  • possible duplicate of How do I copy a file in python? Commented Aug 21, 2012 at 12:51

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

You're so fast. I don't know why I even try, ha
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?
@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)
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.

4 Comments

It matters if file1 is 10Gb in size. :)
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 :)
Which brings up another good point -- on a homework question, do you really want to give the answer outright like this?
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 stackoverflow.com/q/123198/589206 :) Maybe I should mark this question as a duplicate?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.