[Tutor] how to read from a txt file

Alan Gauld alan.gauld at freenet.co.uk
Mon Feb 14 01:11:26 CET 2005


> what i know (chapter 7 of the tutorial):
> 1) first, to open a txt file, i can use open() say:
>                 f = open(*.txt, r)
> a user can use the notepad to create the text file so i'll just open
> it for reading. my problem now would be on reading the contents of
the
> file.

OK So far

> 2) f.read(size), since my data ranges from 0-1200, size = 2 for each
read.

you probably want to read it line by line, either using readline
or the simpler:

for line in f:

> 3) should i do this:
>        for data in range (1, 96,1):
>             f.read(2)

Nope, read is way too complicated.

> 4) since f.read() returns string, how would i convert this back to
> decimal value, since i would need the decimal value for the serial
> part.

You can convert a string to a floating point number using the
float() function.

HTH

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld



More information about the Tutor mailing list