[Tutor] really dumb questions

alan.gauld@bt.com alan.gauld@bt.com
Sun, 10 Feb 2002 23:29:18 -0000


Just back from a week vacation so jumping in late...

> > I know that there is writelines, but as usual i can't 
> figure out based on the Python documentation which hardly 
> ever gives illustrative examples.

Thats why Beasleys book is good - it adds the examples ;-)

> >>> scooby_file=open("scooby.txt","w")
> >>> scooby_file.writelines(["Scooby","Dooby","Doo"])
> >>> scooby_file.close()
> 
> Yields the file scooby.txt with the following data in it:
> ScoobyDoobyDoo

And if you want it on separate lines just add a '\n' to 
each item:

f.writelines(map(lambda s: s+'\n', ["Scooby", "Dooby", "Doo"]))

Or do it more explicitly in a loop:

for line in ["Scooby", "Dooby", "Doo"]:
    line = line + '\n'
    f.write(line)

That's all writelines() does internally, (without the \n malarky)
its nothing magic, just a handy shortcut to a common operation...

> > My other dumb question is this: how do i print a list 
> without the leading and trailing brackets and commas? 

> for item in [1,2,3]:
>     print item,           #don't miss that comma on the end, 

But he asked for f.write not print so...

s = ''
for item in [1,2,3]:
    s = s+str(item) # just convert to a string and concatenate
f.write(s)          # then write the final string

> add the `x` thing it works but it adds single quotes to the 
> output. How do you suppress those?

You don't need to. The interpreter adds those to show that 
its a string. If you assign the result to a striong then 
write the string it should work just fine:

> 'x' thing? You've lost me there.

Its the backtick technique for converting to a string.

> current_time=time.time()
> time_file.write(str(current_time))

Yep, just like that... Do you see a trend yet?

> ...the first element of sys.argv should give you 
> what you want. ie.:
> 
> import sys
> program_name=sys.argv[0]

And you could use the os.path functions to prepend 
the current directory if desired.

prog_path = os.path.join(os.getcwd(),sys.argv[0])

Note: that's not tested but something very similar 
should work!

Alan g.