help with lists and writing to file in correct order

homepricemaps at gmail.com homepricemaps at gmail.com
Tue Dec 27 23:11:59 EST 2005


hey steven-your examlpe was very helpful. is there a paragraph symbolg
missing in

fp.write("Food = %s, store = %s, price = %s\n" % triplet


Steven D'Aprano wrote:
> On Mon, 26 Dec 2005 20:56:17 -0800, homepricemaps wrote:
>
> > sorry for asking such beginner questions but i tried this and nothing
> > wrote to my text file
> >
> > for food, price, store in bs(food, price, store):
> > 		out = open("test.txt", 'a')
> > 		out.write (food + price + store)
> >         	                out.close()
>
> What are the contents of food, price and store? If "nothing wrote to my
> text file", chances are all three of them are the empty string.
>
>
> > while if i write the following without the for i at least get
> > something?
> > out = open("test.txt", 'a')
> > out.write (food + price + store)
> > out.close()
>
> You get "something". That's not much help. But I predict that what you are
> getting is the contents of food price and store, at least one of which are
> not empty.
>
> You need to encapsulate your code by separating the part of the code that
> reads the html file from the part that writes the text file. I suggest
> something like this:
>
>
> def read_html_data(name_of_file):
>     # I don't know BeautifulSoup, so you will have to fix this...
>     datafile = BeautifulSoup(name_of_file)
>     # somehow read in the foods, prices and stores
>     # for each set of three, store them in a tuple (food, store, price)
>     # then store the tuples in a list
>     # something vaguely like this:
>     data = []
>     while 1:
>         food = datafile.get("food")  # or whatever
>         store = datafile.get("store")
>         price = datafile.get("price")
>         data.append( (food,store,price) )
>     datafile.close()
>     return data
>
> def write_data_to_text(datalist, name_of_file):
>     # Expects a list of tuples (food,store,price). Writes that list
>     # to name_of_file separated by newlines.
>     fp = file(name_of_file, "w")
>     for triplet in datalist:
>         fp.write("Food = %s, store = %s, price = %s\n" % triplet
>     fp.close()
> 
> 
> Hope this helps.
> 
> 
> 
> -- 
> Steven.




More information about the Python-list mailing list