我尝试在while循环中将不同的内容写入文本文件,但它只写入一次。我想写一些东西到ungrated.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,或者更好的方法是再次遍历列表:而且
wring = wf.write(blue[i] + " is " + "Unmigrated\n")
将wring
设置为None
,这是write返回的结果,因此可能没有任何实际用途最后,使用一个空白的expect通常不是一个好主意,捕获您期望的特定异常,并在出现错误时记录或至少打印
使用requests库,我将分解您的代码,如下所示:
我不确定
'legacy'
在代码中的位置,我将把这个逻辑留给您。您还可以直接在file对象上迭代,这样就可以忘记将行拆分为blue
尝试:
但这将覆盖文件的所有内容。 相反,如果要附加到文件,请使用:
如果选择不使用
with
语法,请记住关闭文件。 阅读更多信息: https://docs.python.org/2/library/functions.html#open相关问题 更多 >
编程相关推荐