代码之家  ›  专栏  ›  技术社区  ›  hachemon

如何在python中将输出文本附加到文件中

  •  0
  • hachemon  · 技术社区  · 3 年前

    我正试图将代码的打印输出附加到python中的一个文件中。下面是代码示例 test.py :

    import http.client
    
    conn = http.client.HTTPSConnection("xxxxxxxxxxxx")
    
    headers = {
        'Content-Type': "xxxxxxxx",
        'Accept': "xxxxxxxxxx",
        'Authorization': "xxxxxxxxxxxx"
        }
    
    conn.request("GET", "xxxxxxxxxxxx", headers=headers)
    
    res = conn.getresponse()
    data = res.read()
    
    print(data.decode("utf-8"))
    

    这会在我的控制台上打印出大量的文本。

    我的目标是获取输出并将其发送到任意文件。我能想到的一个例子是 python3 test.py >> file.txt 这显示了该文本文件的输出。

    然而,有没有一种方法可以运行类似于 test.py >> file.txt 但是在python代码中?

    0 回复  |  直到 3 年前
        1
  •  1
  •   Mureinik    3 年前

    你可以 open 文件处于“a”(即附加)模式,然后 write 对它:

    with open("file.txt", "a") as f:
       f.write(data.decode("utf-8"))
    
        2
  •  1
  •   MrDiamond    3 年前

    您可以使用包含的模块写入文件。

    with open("test.txt", "w") as f:
        f.write(decoded)
    

    这将获取解码后的文本并将其放入名为 test.txt

    import http.client
    
    conn = http.client.HTTPSConnection("xxxxxxxxxxxx")
    
    headers = {
        'Content-Type': "xxxxxxxx",
        'Accept': "xxxxxxxxxx",
        'Authorization': "xxxxxxxxxxxx"
    }
    
    conn.request("GET", "xxxxxxxxxxxx", headers=headers)
    
    res = conn.getresponse()
    data = res.read()
    
    decoded = data.decode("utf-8")
    print(decoded)
    
    with open("test.txt", "w") as f:
        f.write(decoded)