我试图在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
答案 0 :(得分:3)
你继续覆盖在循环中用w
打开文件,这样你只能看到写入文件的最后一个数据,要么在循环外打开文件,要么打开a
来追加。打开一次将是最简单的方法,你也可以使用范围而不是你的更好或更好再次迭代列表:
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
这是写入返回的内容,因此可能没有任何实际用途。
最后使用空白期望通常不是一个好主意,捕获您期望的特定异常并记录或至少在出现错误时打印。
使用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
。
答案 1 :(得分:0)
尝试:
with open("filename", "w") as f:
f.write("your content")
但是这会覆盖文件的所有内容。 相反,如果要附加到文件,请使用:
with open("filename", "a") as f:
如果您选择不使用with
语法,请记得关闭该文件。
在这里阅读更多:
https://docs.python.org/2/library/functions.html#open