简体   繁体   English

如何在Python中将变量打印到文本文件?

[英]How To Print Variable To A Text File In Python?

Hello i am working on a project that prints extracted url to a text file.... 您好,我正在一个项目中,将提取的url打印到文本文件中。

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 ...... 我在我的python程序中需要一点帮助,这无法将所有提取的url写入文件,而这仅将最后一个url写入文件......

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 !! 对不起英语不好..请帮助!

Use a to append, each time you open using w you overwrite, appending will append after any existing lines: 使用a追加,每次使用w打开时,追加都会在任何现有行之后追加:

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 我还在写操作中添加了\\n ,否则所有数据都将放在一行中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM