Kalec
Kalec

Reputation: 2891

Python trying to write string to file then read string and eval, but something went wrong

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:

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

My problem is when I look into the file ... it's not really a string because it lacks the apostrophes <"> 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-)

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)

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.

Upvotes: 1

Views: 409

Answers (1)

Raymond Hettinger
Raymond Hettinger

Reputation: 226754

To handle your immediate problem, change the line load_stack = str(stack) to load_stack = repr(stack). That will add the apostrophes.

Afterwards, you may want to look at the csv module or shelve module. Both are easy to use and will take care of many of the low level details.

Upvotes: 2

Related Questions