-2

I've searched around and have not been able to find a solution to my specific problem. What i am trying to do is take a text file, where I have each line of the file hold a variable.

in the text file line by line i have

health == 1099239
gold == 123
otherVar == 'Town'

The problem with this is I cant get them separated into different variables instead of just one variable with all the information in it.

Currently i have this as the test for saving into the file

SaveFileName = input('What would you like to name your save: ')
f = open(SaveFileName + '.txt','w+')
health = input('Health: ')
gold = input('Gold: ')
otherVar = input('Other: ')
otherVar = ("'" + otherVar + "'")
f.write('health == ' + health +'\ngold == ' + gold + '\notherVar == ' + otherVar)
print('done')
f.close()
print('closed')

My problem is not with saving, as this seems to work exactly as intended.

Here's the loading

SaveFileName = input('Save name to load: ')
global health
global gold
global otherVar
health = 100
gold = 1000
otherVar = 'null'
def pause():
    pause = input('Press enter to continue. ')
F = open(SaveFileName + '.txt')
for line in F:
    eval(F.readline())
print(health)
pause()
print(gold)
pause()
print(otherVar)
pause()

When i run the Loading file it allows me to input the save file name, then returns this on loading

Traceback (most recent call last):
  File "C:/Users/Harper/Dropbox/Python programming/Test area/Load file test.py", line 12, in <module>
    eval(F.readline())
  File "<string>", line 0

    ^
SyntaxError: unexpected EOF while parsing

4 Answers4

2

Do this to get your result

F = open(‘file.txt’)
for line in F:
    eval(F.readline())

This will read each line and evaluate the line as python not just a string.

2

you can put this in dictionary, and get the value by key

datas = {}

with open('demo.txt') as f:
    for line in f.readlines():
        key, value = line.split('=')
        datas[key.strip()] = value.replace("'", '').strip()

print(datas)

Output

{
'name': 'John',
'health': '100',
'gold': '75',
'currentCell': 'Town'
}
Druta Ruslan
  • 7,171
  • 2
  • 28
  • 38
1
f = open('your_file_name.txt')
for line in f:
    exec(line)

Basically, you can use exec ask the Python interpreter to run each line.

user3100235
  • 127
  • 3
1

You should read in the file, spilt it into lines. Split each line at '=' into values, put all things into a dictionary and maybe parse anything not inside '....' as integer, all others as string:

# filename
fn = "file.txt"

# create file
with open(fn,"w") as f: 
    f.write("""name = 'John'
health = 100
gold = 75
currentCell = 'Town'""")

# read file
with open(fn,"r") as f:
    # read all lines, split into lines, string the \n
    t = [x.strip() for x in f.readlines()]

print(t)

Output:

["name = 'John'", 'health = 100', 'gold = 75', "currentCell = 'Town'"]      

Then you make it into a dictionary:

# create a dictionary from the lines - it will:
#  - for each line split it at = into 2 things
#  - remove whitespaces from each thing
#  - add it into a dictionary, first value as key, second as value
#  - if the second starts with a ' - it will strip the spaces and ' on front and back
#    else it will convert it to an integer 

dictionary = {a.strip(): int(b)    # key : value if condition true
              if not b.strip().startswith("'") 
              else b.strip().strip("'")  # value if condition false
              for a,b in (l.split("=") for l in t if l)}

print(dictionary)

Output:

{'name': 'John', 'health': 100, 'gold': 75, 'currentCell': 'Town'}

You can access the values using dictionary['name'] to get 'John'

Limitations:

  • you can not have the same key twice inside your file
  • you should not have any empty lines or lines w/o = in the file, you would have to adapt the code
  • it only understands string and int so far, if you use other things you need to adapt the dict-generator-code
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69