[pythonvis] How To read a text file

  • From: "Richard Dinger" <rrdinger@xxxxxxxxxx>
  • To: <pythonvis@xxxxxxxxxxxxx>
  • Date: Tue, 20 May 2014 08:25:28 -0700

I am proposing to send out a series of short demonstrations scripts that show a 
way of doing common programming tasks.  I do not claim these to be the best 
way, just a way.  These scripts may cover material not yet covered in the book 
or tutorial you are studying, so you will have to do some digging on your own.

At the meeting the demonstration suggested was a program that counted instances 
of words in a text file.  After writing the program last night, I think it is 
too complex to show all at once, so I intend to send it out in stages.  In this 
first stage the program opens and reads a file of your choice and then closes 
the file.

This demonstration script will eventually show a function that opens a file, 
reads it a line at a time, splits it into words and returns a dictionary of 
word->count values.  A simple driver for the function is shown at the end of 
the file.

Try to figure this out on your own by looking through the Python tutorial 
provided with Python or one of the recommended books.  Of course, you can ask 
on the list or at the chat meetings as well.

Richard
# wordCount0.py open and read a text file
""" This script shows how to:
- open a text file
- read file by line
- close file
"""


def counter(file):
  # Open and read file

  # open file for reading
  inFile = open(file, 'r')

  # read file by lines
  for line in inFile:
    #print 'line', line.strip()
    pass
    # process line here
    # end for line loop

  # close open file
  inFile.close()

  # end wordCount function


if __name__ == '__main__':
  # change this to your file name
  file = 'words.txt'

  # run the counter function
  counter(file)
  #exit()

Other related posts:

  • » [pythonvis] How To read a text file - Richard Dinger