简体   繁体   中英

Python Writing to txt error

Im trying to write different things onto a text file in a while loop but it only writes it once. I want to write something to 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

You keep overwriting opening the file with w inside the loop so you only see the last data that was written to the file, either open the file once outside the loop or open with a to append. Opening once would be the simplest approach, you can also use range instead of your while or better again just iterate over the list:

with open("unmigrated.txt", "w") as f: # with close your file automatically
     for ele in blue:
          .....

Also wring = wf.write(blue[i] + " is " + "Unmigrated\\n") sets wring to None which is what write returns so probably not of any real use.

Lastly using a blank expect is usually never a good idea, catch the specific exceptions you expect and log or at least print when you get an error.

Using the requests library, I would break up your code doing something like:

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))

I am not sure where 'legacy' fits into the code, that logic I will leave to you. You can also iterate directly over the file object so you can forget about splitting the lines into blue .

try:

with open("filename", "w") as f:
    f.write("your content")

But that will overwrite all contents of the file. Instead, if you want to append to the file use:

with open("filename", "a") as f:

If you choose to not use the with syntax, remember to close the file. Read more here: https://docs.python.org/2/library/functions.html#open

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM