gpt4 book ai didi

Python 写入 txt 报错

转载 作者:太空宇宙 更新时间:2023-11-04 01:01:40 26 4
gpt4 key购买 nike

我试图在 while 循环中将不同的东西写入文本文件,但它只写入一次。我想写点东西到unmigrated.txt

import urllib.request
import json
Txtfile = input("Name of the TXT file: ")
fw = open(Txtfile + ".txt", "r")
red = fw.read()
blue = red.split("\n")
i=0
while i<len(blue):
try:
url = "https://api.mojang.com/users/profiles/minecraft/" + blue[i]
rawdata = urllib.request.urlopen(url)
newrawdata = rawdata.read()
jsondata = json.loads(newrawdata.decode('utf-8'))
results = jsondata['id']
url_uuid = "https://sessionserver.mojang.com/session/minecraft/profile/" + results
rawdata_uuid = urllib.request.urlopen(url_uuid)
newrawdata_uuid = rawdata_uuid.read()
jsondata_uuid = json.loads(newrawdata_uuid.decode('utf-8'))
try:
results = jsondata_uuid['legacy']
print (blue[i] + " is " + "Unmigrated")
wf = open("unmigrated.txt", "w")
wring = wf.write(blue[i] + " is " + "Unmigrated\n")
except:
print(blue[i] + " is " + "Migrated")
except:
print(blue[i] + " is " + "Not-Premium")

i+=1

最佳答案

您在循环内用 w 不断覆盖打开文件,因此您只能看到写入文件的最后数据,要么在循环外打开文件一次,要么用 a 打开 追加。打开一次是最简单的方法,您也可以使用 range 而不是 while 或更好地再次遍历列表:

with open("unmigrated.txt", "w") as f: # with close your file automatically
for ele in blue:
.....

同时 wring = wf.write(blue[i] + "is "+ "Unmigrated\n")wring 设置为 None这是 write 返回的内容,因此可能没有任何实际用途。

最后,使用空白 expect 通常不是一个好主意,捕获您期望的特定异常并记录或至少在您遇到错误时打印。

使用 requests图书馆,我会打破你的代码做这样的事情:

import requests


def get_json(url):
try:
rawdata = requests.get(url)
return rawdata.json()
except requests.exceptions.RequestException as e:
print(e)
except ValueError as e:
print(e)
return {}

txt_file = input("Name of the TXT file: ")

with open(txt_file + ".txt") as fw, open("unmigrated.txt", "w") as f: # with close your file automatically
for line in map(str.rstrip, fw): # remove newlines
url = "https://api.mojang.com/users/profiles/minecraft/{}".format(line)
results = get_json(url).get("id")
if not results:
continue
url_uuid = "https://sessionserver.mojang.com/session/minecraft/profile/{}".format(results)
results = get_json(url_uuid).get('legacy')
print("{} is Unmigrated".format(line))
f.write("{} is Unmigrated\n".format(line))

我不确定 'legacy' 在代码中的位置,我将把那个逻辑留给你。您还可以直接遍历文件对象,这样您就可以忘记将行拆分为 blue

关于Python 写入 txt 报错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32554852/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com