Two small problems

Alex Martelli aleaxit at yahoo.com
Mon May 7 11:06:09 EDT 2001


"Martin Johansson" <045521104 at telia.com> wrote in message
news:ZmwJ6.666$Yu6.180187 at newsc.telia.net...
> 1. I have i textfile named links.
> and I want to have the first line in that file as a string.
> h.putrequest('GET', '/vss/handpc/nyheter/0,2183,138_nyheter_1022,00.html')
> instead of /vss/handpc and so on I want the first line from the file how
> could I solve this.

    open('links').readline()

will return the first line of a textfile called 'links' and
residing in the current directory.  Note the trailing '\n',
if present in the file, will ALSO be present in this, so you
might want to write

    open('links').readline().rstrip()

to get a copy with all trailing whitespace removed (the '\n',
but also any trailing blanks, tabs, &c), or other approaches
to massage the line into exactly the shape you desire.


> 2. And then I wonder if there is any method that can delete all lines i a
> textfile??
> like f.delete(all)???????

open('links','w').close()

will overwrite the file called 'links', and residing in the
current directory, with an empty (0-length) file of the
same name.  Is that what you desire...?  Or else, import os,
then os.unlink('links') -- this will delete the file, rather
than leaving it there but with 0 bytes in it.


Alex






More information about the Python-list mailing list