[Tutor] Re: Files and such
David Rock
david at graniteweb.com
Sat Oct 2 18:29:24 CEST 2004
* Prospero <prospero at prosperosisland.co.uk> [2004-09-30 17:45]:
> Greetings!
>
> Still hoping someone can give me an answer on this. (Problem repeated
> below.) It seems such an obvious thing but neither the online
> information I have seen nor the one book I own on Python seem to
> address it.
>
> I need to save some numbers in a text file. This bit I can do no
> problem but then I need a different part of the program to read these
> numbers one set at a time, starting at the beginning and stopping at
> the end. For preference the file should be plain text so that I can
> amend it by hand if necessary. Any clues about how to do this would be
> much appreciated.
>
> The numbers are in groups of six, all single- or double-digit
> integers. The file would be added to one group at a time. The image I
> have in mind is of each group occupying one line, separated either by
> commas or spaces, but this does not matter as long as the format is
> clear enough to allow human editing.
If you are looking to store them as comma separated lists and you are
using Python 2.3, then the csv module is your friend:
http://docs.python.org/lib/module-csv.html
Here is a simple csv reader example:
http://docs.python.org/lib/node549.html
And here is the reader example in action using ipython (I highly
recommend ipython for interactive shell work ;-)
http://ipython.scipy.org/
Contents of sample.csv:
1,2,3,4,5,6
3,5,7,46,77,88
2,6,13,7,23,5
$ ipython
Python 2.3.3 (#1, Jul 6 2004, 06:02:39)
Type "copyright", "credits" or "license" for more information.
IPython 0.6.0 -- An enhanced Interactive Python.
? -> Introduction to IPython's features.
@magic -> Information about IPython's 'magic' @ functions.
help -> Python's own help system.
object? -> Details about 'object'. ?object also works, ?? prints more.
In [1]: import csv
In [2]: reader = csv.reader(file("sample.csv"))
In [3]: for row in reader:
...: print row
...:
['1', '2', '3', '4', '5', '6']
['3', '5', '7', '46', '77', '88']
['2', '6', '13', '7', '23', '5']
As you can see, the csv module will easily create a list by parsing a
comma-separated line of data. I use this a LOT in text processing
applications.
--
David Rock
david at graniteweb.com
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20041002/b54aed73/attachment.pgp
More information about the Tutor
mailing list