472,973 Members | 2,465 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,973 software developers and data experts.

problems writing tuple to log file

i am having a problem writing a tuple to a text file. my code is
below.

what i end up getting is a text file that looks like this

burger, 7up
burger, 7up
burger, 7up

and this is instead of getting a list that should look like this

burger, 7up
fries ,coke
cake ,milk

note that i have print statements that print out the results of the
scraping and they are fine. they print out burger, fries, cake and
then 7up, coke, milk

however there is something faulty in my writing of the tuple to the
text file. perhaps related to the indentation that causes it to write
the same stuff over and over?

for row in bs('div'):

data=[]

for incident in bs('span'):
foodlist = []
b = incident.findPrevious('b')
for oText in b.fetchText( oRE):
#foodlist.append(oText.strip() + "',")
foodlist += oText.strip() + "','"
food = ''.join(foodlist)
print food

for incident in bs('span2'):
drinklist = []
for oText in incident.fetchText( oRE):
drinklist += oText.strip() + "','"
drink = ''.join(drinklist)
print drink


tuple = (food + drink "\n")
data.append(tuple)
f = open("data.txt", 'a')
f.write ( ''.join( tuple ) )

Feb 3 '06 #1
3 2696
lo************@gmail.com wrote:
i am having a problem writing a tuple to a text file. my code is
below.

what i end up getting is a text file that looks like this

burger, 7up
burger, 7up
burger, 7up

and this is instead of getting a list that should look like this

burger, 7up
fries ,coke
cake ,milk

note that i have print statements that print out the results of the
scraping and they are fine. they print out burger, fries, cake and
then 7up, coke, milk

however there is something faulty in my writing of the tuple to the
text file. perhaps related to the indentation that causes it to write
the same stuff over and over?

for row in bs('div'):
What kind of function is 'bs'? Should you use 'row'
(which you are looping over) inside the loop?
Seems that your code is equal to

for row in range(len(bs('div'))):
for incident in bs('span'):
Just like you use 'incident' here, inside the other loop.

foodlist = []
b = incident.findPrevious('b')
for oText in b.fetchText( oRE):
#foodlist.append(oText.strip() + "',")
foodlist += oText.strip() + "','"
food = ''.join(foodlist)
print food

After "print food" you repeat the loop, overwriting "food" until last
round. And after you have found the last "food", you put it in "tuple".
tuple = (food + drink "\n")


A tip: 'tuple' is a built-in function, just like 'open' you use.
This statement overwrites that function with a string.
It is usually a good idea to leave the built-ins as they are,
and use some other names for variables.
Feb 3 '06 #2
lo************@gmail.com wrote:
i am having a problem writing a tuple to a text file. my code is
below.
I'd rather say you are having a problem with logic.
what i end up getting is a text file that looks like this

burger, 7up
burger, 7up
burger, 7up
Which is exactly what one would expect (in the best case...) given the
code you've written.
and this is instead of getting a list that should look like this

burger, 7up
fries ,coke
cake ,milk
however there is something faulty in my writing of the tuple to the
text file.
Nope, the problem is elsewhere.
perhaps related to the indentation that causes it to write
the same stuff over and over?
You clearly have a problem with indentation (hint : use spaces not
tabs), but this is not the cause of your problem.


for row in bs('div'):

data=[]

for incident in bs('span'):
foodlist = []
Do you understand that this reinitialise foodlist on each iteration ?
b = incident.findPrevious('b')
for oText in b.fetchText( oRE):
#foodlist.append(oText.strip() + "',")
foodlist += oText.strip() + "','"
Concatening a string to a list may not exactly do what you think. Try
printing foodlist, you'll be surprised.
food = ''.join(foodlist)
Do you understand that this overwrite 'food' on each iteration ?
print food

for incident in bs('span2'):
drinklist = []
Same observation as above
for oText in incident.fetchText( oRE):
drinklist += oText.strip() + "','"
idem
drink = ''.join(drinklist)
idem
print drink


tuple = (food + drink "\n")
1/ dont use 'tuple' as an identified, it shadows the builtin type tuple.
2/ anyway, this is *not* a tuple. What you get here is a string made of
the concatenation of the actual values of food and drink plus a newline.

Ok, at this stage, the name 'food' *may* exist, in which case it'll be
bound to the value found for the last iteration of the first 'for' loop.
Note that it may also not exist at all, if bs('span') returns an empty
sequence - in which case you'll get a nice NameError exception. Same for
'drink' of course.

data.append(tuple)
Why to you append this to a list that you don't use ?
f = open("data.txt", 'a')
This may fail. Please use a try/except block.
f.write ( ''.join( tuple ) )

And please close the file once done.
Your code is such a mess that it's difficult to know for sure what
you're trying to do - and you don't provide much context (hint : when
asking for help, try and post the minimal *runnable* code that exhibit
your problem - 'runnable' meaning that anyone can run your snippet in
it's python interpreter).

What follows is an attempt at rewriting the whole damn thing so it as at
least a chance to behave sensibly - I wouldn't bet that this actually
what you *should* write but I hope this may help you understand where
your errors are. But please dont ask for further help on this code
before you've folowed a good (preferably programming-newbie oriented)
Python tutorial ('learning to think like a computer scientist' may be a
wise choice).

# -----
data=[]
for row in bs('div'):
foodlist = []
for incident in bs('span'):
b = incident.findPrevious('b')
for oText in b.fetchText( oRE):
foodlist.append(oText.strip())

drinklist = []
for incident in bs('span2'):
for oText in incident.fetchText( oRE):
drinklist.append(oText.strip())
# I suppose you expect to have 1 drink for 1 food
assert len(foodlist) == len(drinklist)
pairs = zip(foodlist, drinklist)
data += pairs

try:
f = open("data.txt", 'a')
except IOError, e:
# handle error here
print "oops, failed to open 'data.txt' : %s" % e
else:
f.write("\n".join(["%s, %s" % pair for pair in data])
f.close()

# -----
A last advice : Python comes with an interactive interpreter, which is a
real powertool for learning, testing and debugging. So *use it*.

HTH
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Feb 3 '06 #3
the, the issue is that the last loop adds the last value of everything
to the data array

Feb 4 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Pat Blair | last post by:
Hello. I'm looking for any information I can get about writing values to keys in the Windows registry when the value type is a multi-string (ie. REG_MULTI_SZ). When I get the value of a...
0
by: Pat Blair | last post by:
Sorry to anyone who read this post, but in case it's useful to anyone: Further experiments reveal that while a tuple comes back if you read a multi-line string, you set the value using a list (not...
20
by: Lucas Raab | last post by:
I'm done porting the C code, but now when running the script I continually run into problems with lists. I tried appending and extending the lists, but with no avail. Any help is much appreciated...
1
by: DJTB | last post by:
zodb-dev@zope.org] Hi, I'm having problems storing large amounts of objects in a ZODB. After committing changes to the database, elements are not cleared from memory. Since the number of...
5
by: homepricemaps | last post by:
if i use the code below to write a list to a file list = (food, price, store) data.append(list) f = open(r"test.txt", 'a') f.write ( os.linesep.join( list ) ) it outputs to a file like this
5
by: eight02645999 | last post by:
hi i have some output that returns a lines of tuples eg ('sometext1', 1421248118, 1, 'P ') ('sometext2', 1421248338, 2, 'S ') and so on ..... I tried this re.sub(r" '() ",'',str(output))...
15
by: manstey | last post by:
Hi, I have a text file called a.txt: # comments I read it using this:
2
by: Michael Glassford | last post by:
The Python 2.5 News at http://www.python.org/download/releases/2.5/NEWS.txt states that Python 2.5 was changed to "Use Win32 API to implement os.stat/fstat. As a result, subsecond timestamps are...
13
by: jubelbrus | last post by:
Hi I'm trying to do the following. #include <vector> #include <boost/thread/mutex.hpp> #include <boost/shared_ptr.hpp> #include <boost/tuple/tuple.hpp> class {
0
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 4 Oct 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
by: Aliciasmith | last post by:
In an age dominated by smartphones, having a mobile app for your business is no longer an option; it's a necessity. Whether you're a startup or an established enterprise, finding the right mobile app...
2
by: giovanniandrean | last post by:
The energy model is structured as follows and uses excel sheets to give input data: 1-Utility.py contains all the functions needed to calculate the variables and other minor things (mentions...
4
NeoPa
by: NeoPa | last post by:
Hello everyone. I find myself stuck trying to find the VBA way to get Access to create a PDF of the currently-selected (and open) object (Form or Report). I know it can be done by selecting :...
3
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be using a very simple database which has Form (clsForm) & Report (clsReport) classes that simply handle making the calling Form invisible until the Form, or all...
1
by: Teri B | last post by:
Hi, I have created a sub-form Roles. In my course form the user selects the roles assigned to the course. 0ne-to-many. One course many roles. Then I created a report based on the Course form and...
3
by: GKJR | last post by:
Does anyone have a recommendation to build a standalone application to replace an Access database? I have my bookkeeping software I developed in Access that I would like to make available to other...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.