This will append to the file and create the file if it does not exist:
import os
#hard code the path to the external file
external_file = 'names.txt'
#if file exists, use it to load name, else ask user
if not os.path.isfile(external_file):
with open(external_file, "a") as f:
pass
#if file exists, use it to load name, else ask user
name = raw_input("What's your name?")
with open(external_file, "r") as f:
lines = f.read().strip().split() # split the names to avoid issues like name "a" in name "al" being True
if name in lines:
print "Hi {}".format(name)
else:
with open(external_file, "a") as f: # using "a" will append to the file
f.write(name)
f.write("\n")
I am not sure on your logic for checking if a user exists as you would need to know the name to check if the users name is already in the file.
This reflects your comments:
import os
#hard code the path to the external file
external_file = 'names.txt'
#if file does not exist ask user for name and save it
if not os.path.isfile(external_file):
name = raw_input("What's your name?")
print "Hi {} I am storing your name".format(name)
with open(external_file, "a") as f:
f.write(name)
else:
# file exists, use it to load name and print
with open(external_file, "r") as f:
name =f.read()
print "Hi {}".format(name)
If the file does not exist, the name cannot be in there so this will ask the user for their name or print "Hi name" if the file does exist