如何将列表的内容传递到现有文件?

时间:2014-08-31 18:04:24

标签: python python-3.x

exchangerates = []
newrate = float(input("Enter amount:"))
with open("ExchangeRates.txt","r") as readfile:
    for line in readfile:
        exchangerates.append(line.strip().split(","))
        for line in exchangerates:
            if line[0] == currency1 and line[1] == currency2:
                line[2] = newrate
                print("The exchange rate for",currency1,"and",currency2,"has been changed to",newrate)
        next
        return 0

此代码有效,但我需要知道如何将上面创建的列表中的信息传递到文件中,显示为“Exchangerates.txt”。我该怎么做?

示例输入和输出:

输入货币1:日元

输入货币2:美元

输入金额:3

日元和美元的汇率已经变为3.0

这是我的代码中发生的情况,这是预期的。但是它没有写入文件并且文件中的信息没有更改,这是我的问题。

2 个答案:

答案 0 :(得分:0)

这样做的一个特别简单的方法就是使用Pickle,就像我认为你正在尝试的那样:

import pickle
try:
    with open("ExchangeRates.txt", "rb") as readfile:
        exchangerates = pickle.load(readfile)
except FileNotFoundError:
    exchangerates = {}

currency1 = input("Enter currency 1: ")
currency2 = input("Enter currency 2: ")
newrate = input("Enter exchange rate: ")

if currency1 in exchangerates:
    if currency2 not in exchangerates[currency1] or exchangerates[currency1][currency2] != newrate:
        exchangerates[currency1][currency2] = newrate
        print("The exchange rate for",currency1,"and",currency2,"has been changed to",newrate)
else:
    exchangerates[currency1] = {currency2: newrate}
    print("The exchange rate for",currency1,"and",currency2,"has been changed to",newrate)

with open("ExchangeRates.txt", "wb") as writefile:
    pickle.dump(exchangerates, writefile)

请注意,这会将汇率存储为字典,如:{'USD': {'GBP': 1.6, 'YEN': 3}}。如果需要的话,添加/检查并更新反向汇率也相当简单。

答案 1 :(得分:0)

您可以采用更简单的方法来实现:

f = open("ExchangeRates.txt","r")
exchangerates = f.read()
f.close()


lines = exchangerates.split("\n")

# do the stuff you want to the list with the loops in list of lines

exchangerates = "\n".join(lines)

f = open("ExchangeRates.txt","w")
f.write(exchangerates)
f.close()