[Tutor] sorting and writing to data file
Alan Gauld
alan.gauld at btinternet.com
Sun Feb 2 15:10:16 CET 2014
On 02/02/14 03:08, adrian wrote:
> Newbie here. I have a data (.dat) file with integers (2,9,1,5,7,3,9) in
> it just as shown.
In your code below you use a hard coded list not a data file?
> lab3int=[2,9,1,5,7,3,9]
> lab3int.sort()
> print(lab3int)
So far so good.
> lab3int=open('lab3int.dat','w')
But now you've reassigned lab3int to the file object
so you threw away all your data. You need a separate
variable to store the file pointer.
Lets call it intFile...
> lab3int.write()
Would now become
intfile.write(<your data goes here>)
But your data is a sorted list of integers so you need
to convert that to a string before you can write it
to a text file.
You need a loop such as
for item in lab3int:
intFile.write( str(item) )
If you had a lot of data you might want to think
about adding some newlines when you write too...
hth
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list