open()写入我的文件吗?

2024-09-28 14:18:03 发布

您现在位置:Python中文网/ 问答频道 /正文

除了终端输出,我真的没什么好说的

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添加到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文件。那里什么都没有!你知道吗

请帮帮我!你知道吗


Tags: 文件pyreadinputtypecodeopenpickle
1条回答
网友
1楼 · 发布于 2024-09-28 14:18:03

线路

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

打开要写入的文件并删除文件的所有内容。将此行移到实际要写入文件的位置(就在pickle.dump之前)。你知道吗

相关问题 更多 >