我正在尝试学习如何pickle在python中保存对象.但是,当我使用下面的示例代码时,我收到以下错误:io.UnsupportedOperation: read追溯到favorite_color = pickle.load(f_myfile).我找不到这个特殊错误的好解释.我做错了什么,如何纠正?
import pickle # or import cPickle as pickle
# Create dictionary, list, etc.
favorite_color = { "lion": "yellow", "kitty": "red" }
# Write to file
f_myfile = open('myfile.pickle', 'wb')
pickle.dump(favorite_color, f_myfile)
f_myfile.close()
# Read from file
f_myfile = open('myfile.pickle', 'wb')
favorite_color = pickle.load(f_myfile) # variables come out in the order you put them in
f_myfile.close()
Run Code Online (Sandbox Code Playgroud) 我正在努力在一个腌制文件中附加一个列表.这是代码:
#saving high scores to a pickled file
import pickle
first_name = input("Please enter your name:")
score = input("Please enter your score:")
scores = []
high_scores = first_name, score
scores.append(high_scores)
file = open("high_scores.dat", "ab")
pickle.dump(scores, file)
file.close()
file = open("high_scores.dat", "rb")
scores = pickle.load(file)
print(scores)
file.close()
Run Code Online (Sandbox Code Playgroud)
我第一次运行代码时,会打印出名称和分数.
第二次运行代码时,它会输出2个名称和2个分数.
第三次运行代码时,它会输出第一个名称和分数,但它会覆盖第二个名称并使用我输入的第三个名称和分数进行分数.我只是想让它继续添加名称和分数.我不明白为什么它保存名字并覆盖第二个名字.
我正在研究一个问题,即创建一个程序来获取文件的用户输入,然后在文件中删除用户指定的字符串.我不确定如何从我所拥有的(下面)到问题所要求的内容.一如既往,非常感谢任何和所有的帮助.
def main():
outfile = open(input("Enter a file name: "), "a")
string = input("Enter the string to be removed: ")
for string in outfile.readlines():
string = string.replace(string, "")
outfile.close()
print("Done")
main()
Run Code Online (Sandbox Code Playgroud)
我采取了其中一个建议,并尝试让它工作,但正如我在下面的评论中所说,下面的代码不会返回错误,它会创建一个空文件.我错过了将新文件作为删除字符串的旧文件而丢失的内容?
def main():
inpath = input("Enter an input file: ")
line = input("Enter what you want to remove: ")
outpath = input("Enter an output file: ")
with open(inpath, "r") as infile, open(outpath, "w") as outfile:
for line in infile:
outfile.write(line.replace(line, "") + "\n")
print("Done.")
main()
Run Code Online (Sandbox Code Playgroud)