我正在尝试将一些数据保存到dict中,然后保存到csv文件中。唯一的问题是我想永久保存csv文件,以便我可以在以后重新启动程序时重新使用它。例如,如果我输入一些数据,它将显示更新的dict和csv文件(如果我用excel打开csv文件,它将显示输入)。但是当我关闭程序并重新启动它并给出一些新的输入时,它将重置dict和csv数据。如何保存数据并只更新文件? 这是我的代码,这里的评论并不重要。
# Writing
import csv
with open("inkomsten.csv", "r") as f:
reader = csv.reader(f, delimiter=":")
# Dicts van de data
inkomsten = {}
uitgaven = {}
##############################
它只关注" Inkomsten"此刻。
# Inkomsten updaten
def toevoegenIn():
bron = str(raw_input("Welke bron wilt U toevoegen? "))
bedrag = int(input("Welk bedrag hoort daarbij? "))
inkomsten[bron] = bedrag
# Uitgaven updaten
def toevoegenUit(bron, bedrag):
uitgaven[bron] = bedrag
##############################
# Totaal bedragen updaten
def totaalIn():
waarde = inkomsten.values()
totaal = 0
for i in waarde:
totaal += i
print totaal
def totaalUit():
waarde = uitgaven.values()
totaal= 0
for i in waarde:
totaal += i
print totaal
##############################
toevoegenIn()
print inkomsten
totaalIn()
with open("inkomsten.csv", "wb") as g:
writer = csv.writer(g, delimiter=":")
writer.writerows(inkomsten.items())
答案 0 :(得分:1)
要将新数据附加到现有文件,您需要在将文件从“wb”打开到“ab”之类时更改访问模式。
查看阅读文件here的教程点页面,在开放功能部分下面有一个表格,其中有不同的选项可用。我知道这个例子不是使用csv模块,但它们似乎有用,我过去曾使用过像'ab'这样的一些模块。
答案 1 :(得分:0)
让我们在这里做几个大的假设...如果他们错了,请给我留言,我会尝试编辑我的答案,使其更适合你的问题。
我们假设以下内容:
<key: value>
结构。这种结构非常适合python dict
key
s(左栏中的项目)在文件中不能出现多次考虑到这些限制,您可以执行以下操作(代码中的注释以及用于调试目的的一些额外print
语句)
import csv
def toevoegenIn():
bron = str(raw_input("Welke bron wilt U toevoegen? "))
bedrag = int(input("Welk bedrag hoort daarbij? "))
return {bron: bedrag}
if __name__ == '__main__':
# Step 1: Load all the data in a dictionary. The cells might come with
# undesired extra spaces in them. Use strip to remove those.
loaded_data = {}
with open('test.csv', 'r') as csv_file_r:
reader = csv.reader(csv_file_r, delimiter=':')
loaded_data = {}
for row in reader:
loaded_data[row[0].strip()] = int(row[1].strip())
print "Initial data: %s" % loaded_data
# Step 2: Ask the user what data to change.
# The toevoegenIn function will return a
# one-key dictionary.
change_data = toevoegenIn()
# Step 3: Use dict.update to update your initial data with the
# dict retrieved above.
# If the modified key already existed in the original dict,
# it will be modified to the value entered by the user.
# If the key wasn't in the original dict, it'll be added.
loaded_data.update(change_data)
print "Updated data: %s" % loaded_data
# Step 4: Write the new data. I put it into a new file, just
# in case you don't wanna overwrite the original one. If
# you do want to overwrite, just change the file's name to
# the original file.
with open('test.csv.new', 'w') as csv_file_w:
writer = csv.writer(csv_file_w, delimiter=':')
for key, val in loaded_data.items():
writer.writerow([key, val])
# Make a quick confirmation read:
with open('test.csv.new', 'r') as f:
print "new_contents:\n%s" % f.read()
哪个输出:
Initial data: {'BD': 69, 'AH': 250, 'BC': 100}
Welke bron wilt U toevoegen? BC
Welk bedrag hoort daarbij? 150
Updated data: {'BD': 69, 'AH': 250, 'BC': 150}
new_contents:
BD:69
AH:250
BC:150