【问题标题】:How would I save this output into a text file in python?如何将此输出保存到 python 中的文本文件中?
【发布时间】:2016-11-12 06:43:32
【问题描述】:

我正在运行 python 2.7

import requests

count = 1000
while count <= 10000:
    count += 1
    user = requests.get("https://api.roblox.com/Users/" + str(count)).json()    ['Username']
    print (user)

谢谢!

【问题讨论】:

  • fo = open("foo.txt", "wb") fo.write(user)
  • @OmidCompSCI 和fo.close()
  • @Rakesh_K 正确。
  • @Rakesh_K> 或者更确切地说,使用with,避免与异常相关的问题。

标签: python output


【解决方案1】:

with 语句中使用open 文件,如下所示:

import requests

count = 1000
with open('output.txt', 'w') as f:
    while count <= 10000:
        count += 1
        user = requests.get("https://api.roblox.com/Users/" + str(count)).json()['Username']
        print (user)
        f.write(user + '\n')

【讨论】:

    【解决方案2】:

    使用 Python 的with,打开你的输出文件,这样文件之后会自动关闭。其次,使用range() 为您提供所有号码更有意义,format 可用于将号码添加到您的 URL,如下所示:

    import requests
    
    with open('output.txt', 'w') as f_output:
        for count in range(1, 10000 + 1):
            user = requests.get("https://api.roblox.com/Users/{}".format(count)).json()['Username']
            print(user)
            f_output.write(user + '\n')
    

    然后将每个条目写入文件,每个条目后面都有一个换行符。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-04
      • 1970-01-01
      • 1970-01-01
      • 2014-09-21
      • 2021-10-16
      相关资源
      最近更新 更多