loop though textfiles

Remco Gerlich scarblac at pino.selwerd.nl
Mon May 14 10:59:00 EDT 2001


Martin Johansson <045521104 at telia.com> wrote in comp.lang.python:
> How can I do if I want to do a searchmethon on several textfiles? Can I use
> fileinput and how should I do?
> It must be some kind of loop.
> this is the lines I want to do on every textfile.
> 
> word = raw_input("skriv ett ord: ")
> c=open('01_10_Maj_12_360,2183,122_nyheter_1022,00.txt', 'r')
> textstring = c.read()
> index = string.find(textstring, word)
> index = string.find(string.lower(textstring), string.lower(word))
> if index > 0:
>     print "do exists"
> else:
>     print "do not exist"

Note that if index == 0, the string does occur in the text (at the very
start). It's -1 when it's not there.

Fileinput works when you need to do something line by line on multiple
files. Since you only care whether the string occurs in the whole file, it's
easier to just loop over the list of files and read them in:

import glob, string

word = string.lower(raw_input("Schrijf het woord:"))

for f in glob.glob("*.txt"): # Get all text files and loop over them
   try:
      filecontents = open(f,'r').read()
   except IOError:
      # If something went wrong, ignore this file
      continue
   index = string.find(string.lower(filecontents), word)
   print "File:", f, ":",
   if index == -1:
      print "Not found"
   else:
      print "Found"

-- 
Remco Gerlich



More information about the Python-list mailing list