Note that there are some explanatory texts on larger screens.

plurals
  1. POPython trying to write string to file then read string and eval, but something went wrong
    text
    copied!<p>I am trying to write a very simple script that would simulate a pocket secretary for my homework, but I have a small issue. I want all my data to be saved in a file (abstract form) each time I exit the program and then when i boot it up I want to read that file, eval(stack) (basically load the data into memory) then verify if it's valid ... anything that isn't is deleted. This is what I've done:</p> <pre><code> def loadToString (stack): f = open ("data.txt", "w") load_stack = str(stack) #convert to string f.write (load_stack) #write in file f.close() def loadFromString (): f = open ("data.txt", "r") load_stack = f.readline() #read string if (load_stack == "" or load_stack == " " or load_stack == None): stack = [] return stack else: stack = eval(load_stack) #trying to convert from string to list f.close () </code></pre> <p>My problem is when I look into the file ... it's not really a string because it lacks the apostrophes &lt;"> thus when I try to "eval (stack)" something goes wrong and my "memory" ends up being empty (when I try to print the stack it's empty -None-)</p> <p>I cannot for the life of me understand why this is happening. Also I'm ok with a quick fix (artificially adding apostrophes in the .txt file)</p> <p>I have no idea how to check if a file is empty or if I read an empty line so I'd also appreciate if you could help me with the "if" statement in "loadFromString". About eval () ... like I said this is just homework so I'm not afraid about any malicious intents.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload