user9760760
user9760760

Reputation: 13

Python - Copying data from one file to another file

I am trying to copy the content of one file to another.

The script successfully copies content to the file but when I try to run READ command with the output file to print the output, it is blank.

from sys import argv
script, inputFile, outputFile = argv
inFile = open(inputFile)
inData = inFile.read()
outFile = open(outputFile, 'w+')
outFile.write(inData)
print("The new data is:\n",outFile.read())
inFile.close()
outFile.close()

Upvotes: 1

Views: 361

Answers (3)

gt6989b
gt6989b

Reputation: 4203

After you are done writing, file pointer is at the end of the file, so no data is there. Reposition pointer to start of the file.

Upvotes: 0

Armin
Armin

Reputation: 168

You forgot to return to the beginning of outFile after writing to it. So inserting outFile.seek(0) should fix your issues.

Upvotes: 1

bruno desthuilliers
bruno desthuilliers

Reputation: 77912

After the write operation the file pointer is at the end of file so you'd need to reset it to the start. Also, the filesystem IO buffers may not have been flushed at that point (you haven't closed the file yet)...

Simple solution: close the outFile and reopen it for reading.

As a side note: always make sure you DO close your files whatever happens, specially when writing, else you may end up with corrupted data. The simplest way is the with statement:

with open(...) as infile, (...) as outfile:
    outfile.write(infile.read())

# at this point both files have been automagically closed

Upvotes: 2

Related Questions