Newbie Question

placid Bulkan at gmail.com
Mon Jun 19 21:39:07 EDT 2006


Saint Malo wrote:
> Thanks!  That helped a lot!  Now, lets say that I just want to display
> one or just a few of the items and not the whole line.  For example,
> the text file contains the following:
>
> red blue yello
> green purple brown
>
>
> If the program searches for blue, i just want it to print blue, not the
> whole line.  If i ask it to find blue and brown, i just want it to
> return those two values.
>
>

search_words = ["red", "brown"]

# Open a file for read
file=open(r'test.txt','r')

# Read each line in file
for line in file

   #Search each line
   for words in search_words:
      if words in line:
          print words

file.close()


* create a list containing search words
* open file for reading
* iterate through each line in the text file
* iterate though each word in search words
* check if the line contains the word your searching for
* print the word if it does
* close file


Cheers

>
>
>
> Andrew Robert wrote:
> > Saint Malo wrote:
> > > I am new to programming, and I've chosen python to start with. I wrote
> > > a simple program that asks several questions and assings each one of
> > > them a variable via raw_input command.  I then combined all the
> > > variables into one like this a = b + c + d.  After this I wrote these
> > > values to a file.  What I want to do now is be able to search through
> > > the file for any data in there.  Is this possible?
> > >
> > Most certainly.
> >
> > It depends on how you want to treat the read data.
> >
> > for example
> >
> >
> > # Open a file for read
> > file=open(r'test.txt','r')
> >
> > # Read each line in file
> > for line in file
> >
> >    #Search each line
> >    if "A" in line:
> > 
> >         print "I found A"
> > 
> > file.close()




More information about the Python-list mailing list