【问题标题】:Is open() writing to my file?open() 正在写入我的文件吗?
【发布时间】:2018-03-10 20:27:23
【问题描述】:

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

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文件。那里什么都没有!

请帮忙!

【问题讨论】:

  • pokedex.py的内容是什么?
  • pickle.load(f_read, "rb") ??? f_read 已经是句柄了。这里出了点问题。
  • @Kevin 它似乎是 API pypi.python.org/pypi/pokedex.py的包装器
  • @n1c9:不,那个文件does not unpickle stuff
  • 添加了文件的内容 - @Kevin 用于添加到泡菜文件中

标签: python pickle


【解决方案1】:

线

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

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

【讨论】:

    猜你喜欢
    • 2023-04-01
    • 2016-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-13
    • 2016-04-23
    • 2011-06-08
    相关资源
    最近更新 更多