HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Saving player name throughout script-launches

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
scriptplayerlaunchesnamesavingthroughout

Problem

I would like to use this in a program to save users' names even after they relaunch the script. I was just wondering if there were some ways I could clean up this code.

Note: this currently was made to not support name changing, but could possibly be implemented in the future.

if os.path.isfile('names.json'): # if there is a file with names...
    text_file = open("names.json") # only open it in normal mode
else: # if not...
    text_file = open("names.json", "w+") # make one

if os.stat("names.json").st_size > 0:
    for line in text_file:
        if line.istitle():
            player_name = line
        else:
            player_name = console.input_alert('What is your name? ').title()
            text_file = open("names.json", "w")
            text_file.write(player_name)
            text_file.close()
else:
    player_name = console.input_alert('What is your name? ').title()
    text_file = open("names.json", "w")
    text_file.write(player_name)
    text_file.close()

Solution

I'm not sure why you are reading all of the file and checking for istitle(). Here I make the assumption that if the file exists, it will always include the player name on the first line.

if os.path.isfile('names.json'):
  with open('names.json') as f:
    player_name = f.readline()
else:
  player_name = console.input_alert('What is your name? ').title()

with open('names.json', 'w') as f:      
    f.write(player_name)


If you want to read the entire file and check for istitle():

player_name = None
if os.path.isfile('names.json'):
  with open('names.json') as f:
      for line in f.readlines():
          if line.istitle():
              player_name = line

with open('names.json', 'w') as f:  
    if player_name is None:
      player_name = console.input_alert('What is your name? ').title()
    f.write(player_name)


You may notice that I do not close the files in either case. That is because the with statement takes care of that for us. See Understanding Python's "with" statement.

Code Snippets

if os.path.isfile('names.json'):
  with open('names.json') as f:
    player_name = f.readline()
else:
  player_name = console.input_alert('What is your name? ').title()

with open('names.json', 'w') as f:      
    f.write(player_name)
player_name = None
if os.path.isfile('names.json'):
  with open('names.json') as f:
      for line in f.readlines():
          if line.istitle():
              player_name = line

with open('names.json', 'w') as f:  
    if player_name is None:
      player_name = console.input_alert('What is your name? ').title()
    f.write(player_name)

Context

StackExchange Code Review Q#55648, answer score: 7

Revisions (0)

No revisions yet.