python - 如何将没有括号和逗号的一行文本转储到 Pickle 文件中
问题描述
我正在编写一个货币转换器,其中一个部分是一个程序,它允许您检查和更改英镑与其他三种货币之间的转换率。虽然实际转换很好,但我在将新费率导出到单行的泡菜文件时遇到了问题。这是因为,汇率以以下格式写入泡菜文件:英镑 1 欧元 1.15 美元 1.3 等。
我将不胜感激任何帮助。
我试过简单地转储一个列表和元组,但它根本不起作用——这不是 Python 错误,而是一个合乎逻辑的错误。
import pickle
Currencies = "Pound-Sterling", "Euro", "US-Dollar", "Japanese-Yen"
Displayed = {}
Exchange_rates = pickle.load(open("rates.pkl","rb"))
print("This program allows you to check and change the currency conversion rates before using the converter program.")
for Line in Exchange_rates:
if not "Pound-Sterling" in Line:
Displayed_key = Line.split(" ")[0]
Displayed_value = Line.split(" ")[1]
Displayed[Displayed_key] = Displayed_value
print("£1 is", Line)
Exchange_rates = {}
New_rates = open("rates.pkl","wb")
pickle.dump("",New_rates)
pickle.dump("Pound-Sterling 1",New_rates)
if getYesNo("Do you want to change an exchange rate for a currency (Y/N):"):
for i in range(1,4):
Currency = Currencies[i]
print("£1 is", Currency, Displayed[Currency])
Prompt = "Please input the new rate for", Currency, ":"
Prompt = " ".join(Prompt)
New_rate = float(input(Prompt))
To_append = Currency, New_rate
pickle.dump(To_append,New_rates)
New_rates.close()
新的 pickle 文件应该是一行的原始格式。相反,它要么在多行,要么不起作用,此外,我无法摆脱括号和逗号。
解决方案
这是您的代码的一个版本,有一些改进
改进:
- 我们不想担心关闭文件,所以我们使用
with open('Currencies.pkl', 'rb') as f:
. 这称为上下文管理器,负责关闭文件。 - 我们想要重用的代码已被放入可调用函数中,例如
print_currencies
- 更改
for i in range(1,4):
为for currency in CURRENCIES:
更具可读性并允许使用任意数量的货币。CURRENCIES
这是一本字典,但可以是一个列表或任何可迭代的。 - 我已经腌制了一个 python 字典对象来存储货币。
需要改进的地方:
- 我在代码中重复了“Currencies.pkl”
- 我不问用户是否要关闭程序
- 如果我想保持货币不变怎么办?
import pickle
# I'll use this later to test if pickle file exists
import os.path
# let's use a default dictionary object
CURRENCIES = {
"Pound-Sterling": 1,
"Euro": 1,
"US-Dollar": 1,
"Japanese-Yen": 1
}
def load_currencies():
"""Load a dictionary object of currencies previously stored"""
with open('Currencies.pkl', 'rb') as f:
dict = pickle.load(f)
return dict
def dump_currencies(dict):
"""Dump a dictionary object of currencies"""
with open('Currencies.pkl', 'wb') as f:
pickle.dump(dict, f)
def print_currencies(dict):
for currency in dict:
if currency != "Pound-Sterling":
print("£1 is", dict[currency], currency)
# this is a special line of code that says "Hey if run me
# directly run this code but if you import me don't"
# - the code that runs effectively starts from here
if __name__ == '__main__':
# if our pickle file does not exist create it using the default
if not os.path.isfile('Currencies.pkl'):
dump_currencies(CURRENCIES)
print("This program allows you to check and change the currency conversion rates before using the converter program.")
CURRENCIES = load_currencies()
print_currencies(CURRENCIES)
answer = input("Do you want to change an exchange rate for a currency (Y/N):")
if answer == 'Y':
for currency in CURRENCIES:
# print(currency)
# print(type(currency)) <-- string
print("£1 is", CURRENCIES[currency], currency)
New_rate = float(input("Please input the new rate for "+currency+":"))
CURRENCIES[currency] = New_rate
dump_currencies(CURRENCIES)
推荐阅读
- windows - 如果我想留出要分配给服务器的地址范围
- reactjs - 内容安全策略不允许 img-src 的外部站点
- visual-studio - Visual Studio 安装程序项目
- c# - 如何强制某个 C# 类型从不用作语句?
- php - Prestashop WebService API - 保存在数据库中的 HTML 富文本
- maven - mvn -version 命令在主目录中运行,但不在其他任何地方
- android - Android Camera2 将流组合成一个超级流
- vba - VBA 时间限制宏
- python - Selenium 切换到弹出窗口
- android - 如何更改回收站视图中的特定项目?