accessing a text file

Alexander Kapps alex.kapps at
Mon Sep 6 00:06:49 CEST 2010

Baba wrote:
> level: beginner
> how can i access the contents of a text file in Python?
> i would like to compare a string (word) with the content of a text
> file (word_list). i want to see if word is in word_list. let's assume
> the TXT file is stored in the same directory as the PY file.
> def is_valid_word(word, word_list)
> thanks
> Baba

Completely untested:

def is_valid_word(word, filename):
     for line in open(filename):
         if word in line.split():
             return True
     return False

More information about the Python-list mailing list