How can I append outpu to a file??

Alex Martelli alex at magenta.com
Sat Aug 19 03:59:13 EDT 2000


"akhar" <akhar at videotron.ca> wrote in message
news:j8nn5.2993$ys4.70008 at weber.videotron.net...
> I am trying to  build a bot that will read links from a given page and
> output them into a file but it has to be able to append to it!! I tried
> rebol first for this project it was very easy but it was not reading some
> sites properly, so I went back to Python now I have coded everything
except
> for appending the links to a file: when I tried to use append it gives me
> name error for ex:
> a = "adsaddsadasd"
> s = "sadsdasdsad"
> a.append(s)
> Traceback (...)
> ...
> nameError: append
> what am I doing wrong??

Are you trying to append to a file, or to a string?  To append to a file,
open it with options 'a', 'r+', or 'a+', seek to end, then just write:

    thefile = open("thefile.txt","r+")
    thefile.seek(0,2)
    thefile.write("another line\n")
    thefile.close()


If you want to append string, just remember strings, like numbers,
are not modifiable objects: you cannot modify an existing string,
but you can compute a new one and bind it to the variable name
you want.  For example, in your code:

    a = a + s

gets the effect you were probably looking for.  But it really has
little to do with appending to a file.

> Also I am trying to have each link on a line but
> they are all outputed to one line, how can I change this?


By making sure you write a '\n' after each string you write.


> I am using re and
> I am finding to be to unpresice compared to rebol for ex:
> for the string http://www.python.com/er/  In rebol I was able to extract
> www.python.com whereas in python it gives me the whole string.. I am lost
in
> python's power!!!

For example:

import re

thehost = re.compile('/([^/]+)/')

maybealink = 'http://www.python.com/er/'

amatch = thehost.search(maybealink)

if amatch:
    # now open a file for append into 'somefile',
    # see above, and:
    somefile.write(amatch.group(1) + '\n')


The parentheses ( ) in the re are for 'grouping' purposes -- i.e.
for extracting parts of what the re has matched.  The .search
method of the compiled re matches anywhere within the arg
string (the .match method would only match from the start).


Alex






More information about the Python-list mailing list