Python写入txt错误

Python写入txt错误,python,Python,我试图在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 =

我试图在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
导入urllib.request
导入json
Txtfile=input(“TXT文件的名称:”)
fw=打开(Txtfile+“.txt”,“r”)
红色=fw.read()
蓝色=红色。拆分(“\n”)
i=0

当i在循环内使用
w
覆盖打开文件时,您只能看到写入文件的最后一个数据,可以在循环外打开文件一次,也可以使用
a
打开以追加。打开一次将是最简单的方法,您也可以使用范围而不是while,或者更好,只需重复列表:

with open("unmigrated.txt", "w") as f: # with close your file automatically
     for ele in blue:
          .....
另外
wring=wf.write(蓝色[i]+”是“+”未分割的\n”)
wring设置为
None
,这是write返回的结果,因此可能没有任何实际用途

最后,使用空白预期通常不是一个好主意,捕获预期的特定异常,并在出现错误时记录或至少打印

使用库,我会分解您的代码,如下所示:

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:
如果选择不将
语法一起使用,请记住关闭文件。 请在此处阅读更多信息:

使用
'a'
打开文件,最好使用
和open(…):