[Tutor] Re: Files and such

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Thu Sep 30 21:23:58 CEST 2004



On Thu, 30 Sep 2004, Prospero wrote:


> 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.


Hi Prospero,


When you're reading lines back from a file, all that Python knows is that
the file contains a bunch of string lines.  For example:

###
[dyoo at shoebox dyoo]$ cat >somenumbers
3
2
1
[dyoo at shoebox dyoo]$ python
Python 2.3.3 (#1, Aug  9 2004, 10:11:39)
[GCC 3.3.3 20040412 (Gentoo Linux 3.3.3-r6, ssp-3.3.2-2, pie-8.7.6)] on
linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>>
>>> lines = myfile.readlines()
>>> lines
['3\n', '2\n', '1\n']
###


So you may need to do some additional interpretation to get back the
numbers instead of the strings.  Python simply doesn't know enough at this
point to guess that those strings are really supposed to be interpreted as
numbers.


But it sounds like the text file that you want to work with will contain
just integers.  One way to transform a string into an integer is through
the 'int()' function:

###
>>> for line in lines:
...     n = int(line)
...     print "I see a", n
...
I see a 3
I see a 2
I see a 1
###


And this will work as long as there's just one number per line. If each
line is tab or comma delimited, then we can first "split" the line, and
then "int()" each chunk:

###
>>> line = 'this,is,a,line,with,commas,separating,columns'
>>> chunks = line.split(',')
>>> chunks
['this', 'is', 'a', 'line', 'with', 'commas', 'separating', 'columns']
###



So the loading of data back from files into Python usually involves
something that looks like:

### Pseudocode
def doLoad():
    for line in some_file:
        break up the line into chunks
        do something (like type conversion) to each chunk
###


Does this make sense so far?  The process here is a little ad-hoc, but
it's usually effective for simple data like this.  *grin* Please feel free
to ask more questions about this.


(Aside: If your file has a bit more regular tab-delimited structure, you
can take advantage of the 'csv' Comma Separated Values parser in the
Standard Library:

    http://www.python.org/doc/lib/module-csv.html
)


Hope this helps!



More information about the Tutor mailing list