[英]Python Writing to txt error
我试图在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而不是你的时间,或者最好只是遍历列表:
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
,这是写操作返回的结果,因此可能没有任何实际用途。
最后,使用空的期望值通常不是一个好主意,捕获您期望的特定异常,并在出现错误时记录或至少打印出来。
使用请求库,我将分解您的代码,例如:
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
。
尝试:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.