【问题标题】:How to append new rows using cvs files?如何使用 cvs 文件追加新行?
【发布时间】:2015-02-13 01:11:58
【问题描述】:
import csv

running = 1

def show_menu():
    print "1. Add"
    print "2. check"
    return input("Please make a selection: ")

def add():
       writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
       writer.writeheader()
       writer.writerow({'username': raw_input('Uid:'), 'password': raw_input('Pass:')})
       print "success!"
       running = 0

while running:
    choice = show_menu()
    if choice == 1:
        with open('names.csv', 'w') as csvfile:
           fieldnames = ['username', 'password']
           add()

我添加的下一个输入是覆盖现有的。如何将新输入附加到旧输入?

【问题讨论】:

    标签: list python-2.7 csv


    【解决方案1】:

    为了追加,您可以以追加模式打开文件。

    open('names.csv', 'a')
    

    【讨论】:

    • 谢谢。它有帮助!你能告诉我如何检查输入是否已经存在。
    • 您正在使用 DictWriter。如果您使用 csv.DictReader(),您应该能够读取现有数据。文档:docs.python.org/2.7/library/csv.html#module-contents
    • 我正在尝试检查我输入的输入是否已经存在于文件中。 reader = csv.DictReader(csvfile) for row in reader: if a == row['username']: 但它似乎不起作用。
    • 如果 a 是正确的用户名,它应该可以工作。你能分享你正在使用的代码吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-23
    • 2012-06-09
    相关资源
    最近更新 更多