Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #73661 > unrolled thread

Python reading and writing

Started byaws Al-Aisafa <geniusrko@gmail.com>
First post2014-06-27 09:12 -0700
Last post2014-06-27 18:25 +0200
Articles 2 — 2 participants

Back to article view | Back to comp.lang.python


Contents

  Python reading and writing aws Al-Aisafa <geniusrko@gmail.com> - 2014-06-27 09:12 -0700
    Re: Python reading and writing Peter Otten <__peter__@web.de> - 2014-06-27 18:25 +0200

#73661 — Python reading and writing

Fromaws Al-Aisafa <geniusrko@gmail.com>
Date2014-06-27 09:12 -0700
SubjectPython reading and writing
Message-ID<6dcdb0ea-387b-4b32-92a8-a4197db5cff9@googlegroups.com>
Why doesn't this code work?
http://pastebin.com/A3Sf9WPu

[toc] | [next] | [standalone]


#73663

FromPeter Otten <__peter__@web.de>
Date2014-06-27 18:25 +0200
Message-ID<mailman.11290.1403886377.18130.python-list@python.org>
In reply to#73661
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)

[toc] | [prev] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web