Python reading and writing

Peter Otten __peter__ at web.de
Fri Jun 27 12:25:55 EDT 2014


aws Al-Aisafa wrote:

> Why doesn't this code work?

> #I want this code to write to the first file and then take the
> #contents of the first file and copy them to the second.
>  
> from sys import argv
>  
> script, file1, file2 = argv
>  
>  
> def write_to_file(fileread, filewrite):
>     '''Writes to a file '''
>     filewrite.write(fileread)
>  
>  
> input_file = open(file1, 'r+w')
> output_file = open(file2, 'w')
>  
> datain = raw_input(">")
> input_file.write(datain)
>  
> print input_file.read()
>  
> write_to_file(input_file.read(), output_file)
> create a new version of this paste

> http://pastebin.com/A3Sf9WPu


> input_file.write(datain)

The file cursor is now positioned after the data you have just written. Then 
you read all data in the file *after* that data. As there is not data (you 
have reached the end of the file) the following prints the empty string:

> print input_file.read()
 
One way to fix this is to move the file pointer back to the beginning of the 
file with

input_file.seek(0)

so that a subsequent

input_file.read()

will return the complete contents of the file. 

For the simple example it would of course be sufficient to reuse datain:

write_to_file(datain, output_file)




More information about the Python-list mailing list