【问题标题】:Python trying to write string to file then read string and eval, but something went wrongPython 尝试将字符串写入文件然后读取字符串和 eval,但是出了点问题
【发布时间】:2011-11-20 19:36:11
【问题描述】:

我正在尝试编写一个非常简单的脚本来模拟我的家庭作业的袖珍秘书,但我有一个小问题。 我希望每次退出程序时我的所有数据都保存在一个文件(抽象形式)中,然后当我启动它时我想读取该文件,eval(stack)(基本上将数据加载到内存中)然后验证是否它是有效的......任何不是的都被删除。 这就是我所做的:

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

我的问题是当我查看文件时...它不是真正的字符串,因为它缺少撇号空的(当我尝试打印堆栈时它是空的 -None-)

我一生都无法理解为什么会发生这种情况。我也可以快速修复(人为在 .txt 文件中添加撇号)

我不知道如何检查文件是否为空或我是否读取了空行,因此如果您能帮助我处理“loadFromString”中的“if”语句,我将不胜感激。 关于 eval() ...就像我说的这只是家庭作业,所以我不怕任何恶意。

【问题讨论】:

    标签: python


    【解决方案1】:

    要处理您当前的问题,请将load_stack = str(stack) 行更改为load_stack = repr(stack)。这将添加撇号。

    之后,您可能需要查看csv moduleshelve module。两者都易于使用,并且可以处理许多底层细节。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-19
      相关资源
      最近更新 更多