Pickle无法正常工作,因此创建的txt文件为空

时间:2014-04-11 10:57:03

标签: python pickle

编写一个程序,用于定义具有以下属性的类Movie:title,director,length(以分钟为单位的电影长度)。创建类Movie的五个对象,将它们腌制并存储在文件中。

#!/usr/local/bin/python
import pickle
class Movies:
    def __init__(self,title,director,length):
        self.x=title
        self.y=director
        self.z=length

def main():
    movie1 = Movies(1,100,10)
    movie2 = Movies(2,200,20)
    movie3 = Movies(3,300,30)
    movie4 = Movies(4,400,40)
    movie5 = Movies(5,500,50)

main()

import pickle
try:
    file=open("movies.txt","w")
    fold =[movie1,movie2,movie3,movie4,movie5]
    pickle.dump[fold,file]

except IOError:
    print("file could not be open")
except ValueError:
    print("could not make list")
except:
    print("some unknown error")
else:
    print("successfully done!")
finally:
    print("printing always")
    file.close()

所以一切正常,但movies.txt文件为空。我是Python的新手,因此我对异常处理的经验较少。但据我所知,泡菜不起作用。

1 个答案:

答案 0 :(得分:1)

您正在函数main中定义影片变量,但它们不会出现在您定义try块的范围内。此外,正如问题的评论中所指出的,您使用错误的语法来调用pickle.dump。它应该使用括号而不是括号括号,即pickle.dump(fold,file)

最后将try块移动到main函数中会使事情按预期工作。像这样:

def main():
    movie1 = Movies(1,100,10)
    movie2 = Movies(2,200,20)
    movie3 = Movies(3,300,30)
    movie4 = Movies(4,400,40)
    movie5 = Movies(5,500,50)

    import pickle
    try:
        file=open("movies.txt","w")
        fold =[movie1,movie2,movie3,movie4,movie5]
        pickle.dump(fold,file)

    except IOError:
        print("file could not be open")
    except ValueError:
        print("could not make list")
    except:
        print("some unknown error")
    else:
        print("successfully done!")
    finally:
        print("printing always")
        file.close()

main()

代码中仍存在一堆样式问题,但这应该可以帮助你了!