1

Hello i am working on a project that prints extracted url to a text file....

I want a little help in my python program it's not working to write all the extracted url to the file whereas this writes the last url only to the file ......

def do_this():
    print url
    text_file = open("Output.txt", "w")
    text_file.write("Extracted URL : %s" % url)

while True:
    url, n = getURL(page)
    page = page[n:]
    if url:
        do_this()
    else:
        text_file.close()
        break

I can't find the solution !!

Sorry For Bad English.. Please Help !!

1
  • I just wanted it to write all the extracted url from a website to a text file.... Commented Dec 25, 2015 at 17:16

1 Answer 1

2

Use a to append, each time you open using w you overwrite, appending will append after any existing lines:

def do_this():
    print url
    text_file = open("Output.txt", "a")
    text_file.write("Purchase Amount: %s\n" % url)

It would probably make more sense to just open once moving the logic into the function, something like:

def do_this(page):
    with  open("Output.txt", "a") as f:
        while True:
            url, n = getURL(page)
            page = page[n:]
            if not url:
                break
            f.write("Extracted URL : %s\n" % url)

I also added a \n to the write or all your data will be on a single line

Sign up to request clarification or add additional context in comments.

1 Comment

Perhaps a brief explanation about the difference between write and append would be beneficial.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.