[Tutor] Reading text files

Kent Johnson kent_johnson at skillsoft.com
Tue Oct 5 18:08:44 CEST 2004

Python text processing tends to be pretty ad hoc. Built-in facilities such 
as string.split and regular expressions are very handy. It's very easy to 
iterate through lines in a text file and extract a bit of information from 
each line. Extracting the second word from each line in a file and building 
a list from the results might be as simple as this:
   data = [ line.split()[1] for line in open('myfile.txt')]

If you can give us a specific example of what you want to do we can point 
you to the tools that can help.

Some things you might be interested in:
I don't have a copy of it handy to see what it says about files, but 
Learning Python tends to have a lot more detail than Python Programming for 
the absolute beginner. If you are finding PPftab too thin you might prefer 
Learning Python: http://www.oreilly.com/catalog/lpython2/
The csv module might be useful depending on the format of your input data: 
The Python Cookbook has a section about text processing: 
David Mertz has an entire book on text processing in Python, but it might 
be difficult for a beginner: http://gnosis.cx/TPiP/


At 09:35 AM 10/5/2004 -0600, Michael Knowles wrote:
>Is there any source which talks in detail about reading text files?  I've
>purchased "Python Programming for the Absolute Beginner" and there is a
>chapter on files and exceptions but it seems pretty basic.  Specifically,
>I'm interested in how I would import specific columns or rows for text
>Thanks in advance,
>Mike Knowles
>Information Systems Analyst
>SI International
>USDA, Forest Service, Rocky Mountain Research Station
>2150 Centre Ave, Bldg A, Suite 361
>Ft. Collins,  CO  80526
>Phone:  (970) 295-5979
>Fax:  (970) 295-5959
>e-mail:  mknowles at fs.fed.us
>Tutor maillist  -  Tutor at python.org

More information about the Tutor mailing list