[Tutor] Field/Variable References

Serdar Tumgoren zstumgoren at gmail.com
Fri Dec 18 16:41:24 CET 2009


> Can someone please let me know how to read a file one record at a time (just
> say fixed block for now - see small example below) and assign columns to
> fields.  Then reference the field names with if-then-else logic.
>
> Sample Fixed Block File:
>
> John98762
> John82634
> John11234
>

Hi John,
Does your file only have one column? In any event, the easiest method
is to open the file as an iterable object and process each line. If
you fire up the python interpreter, you can do something like:

>>> for line in open('/path/to/data_file.txt'):
...         data = line
...         # do stuff with data

The above assumes you only have that one column you showed, which I
imagine is not the case. If you can show us more details about your
data, we could offer other suggestions on how to parse it.

Meantime, you might want to check the below resources on working with files:

http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files
http://www.freenetpages.co.uk/hp/alan.gauld/
http://diveintopython.org/file_handling/file_objects.html

HTH,
Serdar

ps - Apologies to Alan if I provided the outdate URL to his tutorial
(I *thought* I updated, but can't recall for certain)


More information about the Tutor mailing list