更新CSV文件中的特定行 [英] Updating a specific row in csv file
问题描述
我有一个这样的csv文件:
I have a csv file like this:
Name,PhoneNumber,Adress
我想从用户那里获取输入并更改名称.我可以删除整行.
I want to get input from the user and change the name. I can delete the whole row.
name = input("Enter a name : ")
fieldnames = ["name", "number", 'address']
with open('book.csv', 'r') as csvfile, open('outputfile.csv', 'w') as output:
reader = csv.DictReader(csvfile, fieldnames=fieldnames)
writer = csv.DictWriter(output, fieldnames=fieldnames)
for row in reader:
if not name == row['name']:
writer.writerow({'name': row['name'], 'number': row['number'], 'address': row['address']})
shutil.move('outputfile.csv','book.csv')
这是我的删除代码.
推荐答案
如果名称匹配,只需交互提示输入新名称,即可更新row
:
if name matches, just interactively prompt for a new name, updating row
:
for row in reader:
if name == row['name']:
row['name'] = input("enter new name for {}".format(name))
# write the row either way
writer.writerow({'name': row['name'], 'number': row['number'], 'address': row['address']})
此外:某些python 2版本需要open('outputfile.csv', 'wb')
(或者在输出文件中出现空白行),而某些python 3版本则需要open('outputfile.csv', 'w', newline='')
.
Aside: some python 2 versions need open('outputfile.csv', 'wb')
(or you get blank lines in output file) and some python 3 versions need open('outputfile.csv', 'w', newline='')
.
在执行操作时,只需open('outputfile.csv', 'w')
就可以使用最新版本的python 2或python.
Newest releases of python 2 or 3 are ok with just open('outputfile.csv', 'w')
as you're doing.
这篇关于更新CSV文件中的特定行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!