[Tutor] how to read a text file, and find items in it

Alan Gauld alan.gauld at freenet.co.uk
Thu Mar 9 09:00:32 CET 2006


Hi Adam,

Its not really clear what you want us to do, so I;ll just make some
general comments on the code... In future it would help if you tell
us whether there is a problem, and if so what iut is, including any
error text. Or whether you would just like a critique of your code.

> I am trying to learn a bit of python, and thought it would be a challenge
> to make a script that reads a text file and returns all the instances of a 
> word
> I specify. Basically a find and then a list of all the finds.

Basically a python version of the standard grep command... :-)

> I am using a text file with some random words in it to test it out on

> import fileinput
>
> print
> print "Welcome to LIST YOUR FILEINS script"

Instead of two prints you can just print a newline character:

print "\nWelcome to LIST YOUR FILEINS script"

Or use a triple quoted string:

print """
Welcome to LIST YOUR FILEINS script"""

> print "drag'n'drop your script from the Finder here"
> script = raw_input(">")

I assume you are on a Mac? Interestingly I didn't know the Terminal
supported drag n drop from finder. Pretty neat!

> print
> print "The location of your script is"
> print script
> print

Again you could replace all of that with:

print "\nThe location of your script is", script, "\n\n"

Or use string formatting

print "\nThe location of your script is %s\n\n"  %  script

> file=open(script)
> text=file.readlines()
> f = 'file'
> for f in text: print f

you can iterate over the file directly so you could just use

for f in file: print f

But I think you didn't really want to use f.
The for loop replaces the value of f with each line in your file.
What I think you wanted - using more meaningful names! - is:

word = 'file'
for line in file:
   if word in line: print line

HTH,

Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld




More information about the Tutor mailing list