open()写入我的文件?

时间:2018-03-10 20:27:24

标签: python pickle

除了我的终端输出

,我真的没什么好说的
matthew@archey [03:13:31 PM] [~/code] 
-> % python3         
Python 3.6.4 (default, Jan  5 2018, 02:35:40) 
[GCC 7.2.1 20171224] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> f=open("pokemon.pkl", "wb")
>>> pickle.dump({}, f)
>>> f.close()
>>> exit()
matthew@archey [03:15:23 PM] [~/code] 
-> % cat pokemon.pkl 
�}q.%                                                                                                                               matthew@archey [03:15:27 PM] [~/code] 
-> % python3 pokedex.py 
Traceback (most recent call last):
  File "pokedex.py", line 8, in <module>
    pokemon = pickle.load(f_read, "rb")
EOFError: Ran out of input
matthew@archey [03:15:37 PM] [~/code] 
-> % vim pokedex.py 
matthew@archey [03:15:52 PM] [~/code] 
-> % cat pokemon.pkl 
matthew@archey [03:16:02 PM] [~/code] 
-> % 

所有代码:
只是一个注释 - 这会将宠物小精灵添加到pokemon.pkl文件

import pickle

# pokedex pokemon appender

f_read = open("pokemon.pkl", "rb")
f_write = open("pokemon.pkl", "wb")

pokemon = pickle.load(f_read)

f_read.close()

try:
    while True:
        p_name   = input("Name: ")
        p_type   = input("Type: ")
        p_height = input("Height: ")
        p_weight = input("Weight: ")
        pokemon[p_name] = [p_type, p_height, p_weight]

except KeyboardInterrupt:
    pickle.dump(pokemon, f_write)
    print("Exiting...")

所以这就是我所做的:

  • 创建了pickle文件
  • 查看我的pickle文件
  • 我的代码。它出错并说文件'用完了输入'
  • 再次查看了pickle文件。那里什么都没有!

请帮忙!

1 个答案:

答案 0 :(得分:1)

该行

f_write = open("pokemon.pkl", "wb")

打开用于编写的文件并删除所有文件的内容。将此行移动到您实际要写入文件的位置(就在pickle.dump之前)。