On 23/05/15 06:56, Jim Mooney Py3.4.3winXP wrote:
'''I was using with open...:, but I'm printing a header in one function,
calling a looping
function to print detail lines, then returning to the calling function to
print
the footer. But that didn't work since the with statement only seems to work
with the lexical suite and the file wasn't open in the detail print
function.

What does that mean? Did you get an error message? If so what?
Was the file empty? What happened? Be specific.

a way around this, other than passing the file as I have here?

Passing the file object around is good, its not "a way around".
Its what you should be doing. Passing objects into functions and getting a result back is what good programming encourages.
Leaking objects across function boundaries from the outside
(eg with global variables) is bad and should be avoided.


Since this is a file there are enclosing single quotes not visible:

I don't know what you mean by that.
What is a file? The data below?
Why would that put it in enclosing quotes?

"ANTIGUA AND BARBUDA",0,0,0,0,0
"ARGENTINA",37,35,33,36,39
"BAHAMAS, THE",1,1,1,1,1
"BAHRAIN",5,6,6,6,6
"SPANISH INQUISITION, THE, SILLY",10,33,14,2,8

Program follows (py3.4, winxp):'''

htbegin = '''
...
'''

htend = '''
...

'''

def make_lines():
     co2 = open('co2-sample.csv')
     ht = open('output.html', 'w')
     linelist = []
     print(htbegin, file=ht)

Why not just write to the file directly?

ht.write(htbegin)

     for line in co2:
         newlist = line.rsplit(',', 5) # ending is regular so split it out
first
         for token in newlist:         # since split char inside quotes for
nation is problematic

Use the csv file to parse csv files, it is much more reliable and avoids all the strange exceptional cases such as embedded commas,
split lines etc.

             linelist.append(token.strip('"')) # get rid of extra quotes
             linelist[-1] = linelist[-1].strip()
         fprint(linelist, ht)
         linelist = []

I don't think resetting the list adds much value?

     co2.close()
     print(htend, file=ht)

ht.write(htend)

     ht.close()


def fprint(linelist, ht):
     # size formatting irrelevant for HTML
     formatted_string = "<td
class=l>{}</td><td>{}</td><td>{}</td><td>{}</td><td>{}</td><td>{}</td>".format(*linelist)

your table has no rows, is that deliberate? I'd expect a <tr> at the beginning...

     print(formatted_string, file=ht)

ht.write(formatted_string)

     print('</tr>', file=ht)

and now you add a </tr> at the end. Why not just put it
inside the string?


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to