[Tutor] really dumb questions

Jeff Shannon jeff@ccvcorp.com
Mon, 11 Feb 2002 11:13:56 -0800


> > >>> 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"]))
>
> > 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

For both of these, I'd use string.join() (or its string method equivalent):

f.write( '\n'.join( ['Scooby', 'Dooby', 'Doo'] ) )
# equivalent-- f.write( string.join( ['Scooby', 'Dooby', 'Doo'], '\n' ) )

f.write( ' '.join( [1,2,3] ) )
# equivalent-- f.write( string.join( [1, 2, 3], ' ') )
# or also -- f.write( string.join( [1, 2, 3] ) )  # ' ' is the default


> > '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?

Backticks ( `x` ) are equivalent to repr(x), and I'd think that str(x) would be better to use for most of these circumstances.  I'd only use backticks/repr() for debugging and internal purposes;  if I want to write something that is intended for human consumption, str() is the better bet.
Often they yield the same results, but in those cases where there *is* a difference, str() is intended to be more reader-friendly, while repr() is intended to allow the object to be reproduced from the string returned.


> > ...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])

It should also work (though also untested ;) ) to use abspath() --

prog_path = os.path.abspath(sys.argv[0])

This should (I think) work even if someone has called the script with an absolute path, from a different working directory...

Jeff Shannon
Technician/Programmer
Credit International