python3 csv读写_在python3中读取、更新和写入更新的CSV文件
我正在創(chuàng)建一個(gè)應(yīng)用程序來本質(zhì)上充當(dāng)一個(gè)資產(chǎn)數(shù)據(jù)庫(kù),我試圖打開一個(gè)CSV文件,讀取值并相應(yīng)地更新它們。我看到很多關(guān)于如何讀寫CSV文件的教程,但是我找不到一個(gè)詳細(xì)介紹如何迭代CSV文件和更新單個(gè)值的教程。理想情況下,與列表相比,使用字典似乎更容易,因此我可以按關(guān)鍵字(部件名稱)進(jìn)行搜索。它在大多數(shù)情況下都能工作,但是我在將更新后的列表寫入CSV文件時(shí)遇到了問題。我得到了以下錯(cuò)誤:“第155行,書面形式
返回自撰稿人(self.\u dict_to_列表(rowdict))
值錯(cuò)誤:對(duì)關(guān)閉的文件執(zhí)行I/O操作def write(part_name, part_num="null"):
with open("Database.csv", "r") as file_read:
fieldnames=["Part_Name", "Part_Num"]
csv_reader = csv.DictReader(file_read, fieldnames=fieldnames)
temp_list = [] # Create temp copy of the csv file
for line in csv_reader: # Reading the CSV file and storing it in temp_list
temp_list.append(line)
for line in temp_list: # Printing the original list to verify contents were read correctly
print (line)
for line in temp_list: # Reading each element in the list and updating the value if different from the value passed into the function
if (line["Part_Name"] == part_name and line["Part_Num"] != part_num):
line["Part_Num"] = part_num
for line in temp_list: # Printing out the new vesion of the temp_list to verify updates took
print (line)
with open("Database.csv", "w") as file_write:
csv_writer = csv.DictWriter(file_write, fieldnames=fieldnames)
for line in temp_list: # Attempting to write the updated temp_list to the csv file
csv_writer.writerow(line)
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的python3 csv读写_在python3中读取、更新和写入更新的CSV文件的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: vb6 由于超出容量限制 不能创建新事务
- 下一篇: python 接口自动化_Python