在 Python 2.7.11 中将列表保存和加载为 csv 文件
Saving and loading list as csv file in Python 2.7.11
我是 python 的新手。我有一个名为 bank
的列表,它可以是这样的:
bank = [["matt", "passw", 500, {apple:3}], ["luke", "passw123", 800, {google:2}]]
第一个参数:名称(string
)
第二个参数:密码(string
)
第三个参数:现金金额(float
)
第四个参数:字典(动态的,我可以用其他函数改变键和值)(我不知道怎么保存,如果你能告诉我怎么做我很感激,我评论了代码)。
一开始,bank
是一个空白列表,使用一个名为 add_account
的函数,它添加了一个带有 for 参数的新列表。我的目标是创建一个 .csv 文件,在其中保存 bank
,如果我关闭程序,当我重新打开它时,我想加载包含之前保存的 bank
的所有信息的 .csv 文件。
这些是您需要了解的函数,以解决我将要告诉您的问题:
import csv
def loaddata():
f = open('bank.csv','r')
reader = csv.reader(f)
for row in reader:
bank.append(row)
f.close()
def savedata(bank):
f = open('bank.csv','a')
for account in bank:
print account
#4th parameter is wrong, i don't know how to save the dicionary
st = '%s,%s,%f,%s\n' % (account[0], account[1], account[2], account[3])
f.write(st)
f.close()
bank = []
try:
bank.append(loaddata())
except IOError:
print "creating bank"
def add_account(bank):
new=create_account()
bank.append(new)
def create_account():
new_account = [0,0,0,0]
new_account[0] = raw_input('name ')
new_account[1] = raw_input('psw ')
new_account[2] = input('balance ')
new_account[3] = {}
return new_account
问题是当我调用savedata(bank)
将它保存在一个文件中,然后我调用loaddata(bank)
来恢复之前的bank
数据时,bank
被保存了作为单个字符串,因此我不能使用例如第 3 个和第 4 个参数,因为它们被视为字符串而不是浮点数和字典。此外,当我第二次尝试调用 savedata(bank)
时,它当然不起作用(它说第三个参数需要浮点数而不是字符串)。我该如何解决?先感谢您。
最后一件事:savedata(bank)
函数创建了一个名为 none
的对象,而不是通过 "st" 传递的对象,我不知道为什么。
我建议将 bank
写入 pickle
文件,这是一种二进制格式,人类不可读,但 python 很容易读回而不必担心什么应该是 string
什么应该是 int
等等。如果你 google python pickle.
为了便于人们阅读,您不妨在将其保存为 pickle 时也将 bank
保存为 csv 文件,这样您就可以检查实际保存的内容。
import pickle
import csv
def save_bank(bank, f_stem):
"""
Function to save out the bank
Pass in the bank and a file stem 'f_stem' like 'bank1'
This function will then save a 'bank1.csv' and a 'bank1.pickle'
"""
#Save out a csv of the bank so it's human readable
with open(f_stem+".csv", "wb") as out_csv:
csv_out = csv.writer(out_csv, bank)
csv_out.writerow(['Name','password','money','misc']) #Write out a header
for account in bank:
csv_out.writerow(account) #Write out each account as a row
#Save out a pickle of the bank so it's python readable
pickle.dump(bank, open(f_stem+".pickle", "wb"))
def load_bank(f_stem):
"""
Function to load in the bank
Only needs the file stem used to save out the bank, i.e. 'bank1'
"""
bank = pickle.load(open(f_stem+".pickle", "rb"))
return bank
#Make a test bank
test_bank = [["matt", "passw", 500, {"apple":3}],
["luke", "passw123", 800, {"google":2}]]
f_stem = "bank1"
save_bank(test_bank, f_stem) #Save out the test_bank
new_bank = load_bank(f_stem) #Read it back in as a new bank
#See if the read out and in are identical
print "Bank written and read correctly:", test_bank == new_bank
#Print out the new bank read back in
print new_bank
输出:
Bank written and read correctly: True
[['matt', 'passw', 500, {'apple': 3}], ['luke', 'passw123', 800, {'google': 2}]]
感谢您提出完整的问题,如果有问题或解释不当,请告诉我。
我是 python 的新手。我有一个名为 bank
的列表,它可以是这样的:
bank = [["matt", "passw", 500, {apple:3}], ["luke", "passw123", 800, {google:2}]]
第一个参数:名称(string
)
第二个参数:密码(string
)
第三个参数:现金金额(float
)
第四个参数:字典(动态的,我可以用其他函数改变键和值)(我不知道怎么保存,如果你能告诉我怎么做我很感激,我评论了代码)。
一开始,bank
是一个空白列表,使用一个名为 add_account
的函数,它添加了一个带有 for 参数的新列表。我的目标是创建一个 .csv 文件,在其中保存 bank
,如果我关闭程序,当我重新打开它时,我想加载包含之前保存的 bank
的所有信息的 .csv 文件。
这些是您需要了解的函数,以解决我将要告诉您的问题:
import csv
def loaddata():
f = open('bank.csv','r')
reader = csv.reader(f)
for row in reader:
bank.append(row)
f.close()
def savedata(bank):
f = open('bank.csv','a')
for account in bank:
print account
#4th parameter is wrong, i don't know how to save the dicionary
st = '%s,%s,%f,%s\n' % (account[0], account[1], account[2], account[3])
f.write(st)
f.close()
bank = []
try:
bank.append(loaddata())
except IOError:
print "creating bank"
def add_account(bank):
new=create_account()
bank.append(new)
def create_account():
new_account = [0,0,0,0]
new_account[0] = raw_input('name ')
new_account[1] = raw_input('psw ')
new_account[2] = input('balance ')
new_account[3] = {}
return new_account
问题是当我调用savedata(bank)
将它保存在一个文件中,然后我调用loaddata(bank)
来恢复之前的bank
数据时,bank
被保存了作为单个字符串,因此我不能使用例如第 3 个和第 4 个参数,因为它们被视为字符串而不是浮点数和字典。此外,当我第二次尝试调用 savedata(bank)
时,它当然不起作用(它说第三个参数需要浮点数而不是字符串)。我该如何解决?先感谢您。
最后一件事:savedata(bank)
函数创建了一个名为 none
的对象,而不是通过 "st" 传递的对象,我不知道为什么。
我建议将 bank
写入 pickle
文件,这是一种二进制格式,人类不可读,但 python 很容易读回而不必担心什么应该是 string
什么应该是 int
等等。如果你 google python pickle.
为了便于人们阅读,您不妨在将其保存为 pickle 时也将 bank
保存为 csv 文件,这样您就可以检查实际保存的内容。
import pickle
import csv
def save_bank(bank, f_stem):
"""
Function to save out the bank
Pass in the bank and a file stem 'f_stem' like 'bank1'
This function will then save a 'bank1.csv' and a 'bank1.pickle'
"""
#Save out a csv of the bank so it's human readable
with open(f_stem+".csv", "wb") as out_csv:
csv_out = csv.writer(out_csv, bank)
csv_out.writerow(['Name','password','money','misc']) #Write out a header
for account in bank:
csv_out.writerow(account) #Write out each account as a row
#Save out a pickle of the bank so it's python readable
pickle.dump(bank, open(f_stem+".pickle", "wb"))
def load_bank(f_stem):
"""
Function to load in the bank
Only needs the file stem used to save out the bank, i.e. 'bank1'
"""
bank = pickle.load(open(f_stem+".pickle", "rb"))
return bank
#Make a test bank
test_bank = [["matt", "passw", 500, {"apple":3}],
["luke", "passw123", 800, {"google":2}]]
f_stem = "bank1"
save_bank(test_bank, f_stem) #Save out the test_bank
new_bank = load_bank(f_stem) #Read it back in as a new bank
#See if the read out and in are identical
print "Bank written and read correctly:", test_bank == new_bank
#Print out the new bank read back in
print new_bank
输出:
Bank written and read correctly: True
[['matt', 'passw', 500, {'apple': 3}], ['luke', 'passw123', 800, {'google': 2}]]
感谢您提出完整的问题,如果有问题或解释不当,请告诉我。