473,657 Members | 2,405 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.findPr evious('b')
for oText in b.fetchText( oRE):
#foodlist.appen d(oText.strip() + "',")
foodlist += oText.strip() + "','"
food = ''.join(foodlis t)
print food

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


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

Feb 3 '06 #1
3 2745
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('d iv'))):
for incident in bs('span'):
Just like you use 'incident' here, inside the other loop.

foodlist = []
b = incident.findPr evious('b')
for oText in b.fetchText( oRE):
#foodlist.appen d(oText.strip() + "',")
foodlist += oText.strip() + "','"
food = ''.join(foodlis t)
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.findPr evious('b')
for oText in b.fetchText( oRE):
#foodlist.appen d(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(foodlis t)
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.fetchT ext( oRE):
drinklist += oText.strip() + "','"
idem
drink = ''.join(drinkli st)
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(tup le)
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.findPr evious('b')
for oText in b.fetchText( oRE):
foodlist.append (oText.strip())

drinklist = []
for incident in bs('span2'):
for oText in incident.fetchT ext( oRE):
drinklist.appen d(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".jo in(["%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
4564
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 multi-string value using winreg functions, I get a tuple with tuple being a list, and tuple a number. If I try to write such a tuple back into a multi-string value, I get the following exception: ValueError: Could not convert the data to the...
0
1975
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 a tuple). That's sensible and I don't know why this didn't occur to me before I posted. Thanks -----Original Message----- From: Pat Blair
20
2219
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 Please see both the Python and C code at http://home.earthlink.net/~lvraab. The two files are ENIGMA.C and engima.py TIA
1
2912
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 objects I'd like to store in the ZODB is too large to fit in RAM, my program gets killed with signal 11 or signal 9... Below a minimal working (or actually: it doesn't work because of memory
5
1821
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
1612
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)) but it only get rid of the ' and not
15
3656
by: manstey | last post by:
Hi, I have a text file called a.txt: # comments I read it using this:
2
5041
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 reported, the limit on path name lengths is removed, and stat reports WindowsError now (instead of OSError)." Although not mentioned in the Python 2.5 News, apparently there was a similar change on Mac that I'm having some problems with. On the...
13
2953
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
8324
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8740
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8516
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8617
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7353
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4330
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2743
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1970
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1733
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.