Python写入tx

2024-10-01 13:35:30 发布

您现在位置: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 = "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

Tags: txtjsonurlreaduuidisrequestblue
2条回答

继续覆盖在循环内用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'在代码中的位置,我将把这个逻辑留给您。您还可以直接在file对象上迭代,这样就可以忘记将行拆分为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

相关问题 更多 >