Python 写入csv,一次检查一个字符串是否在csv中

Python write to csv, once checked whether a string is in a csv

目前,我有

imported csv

并制作了一个输入变量供用户输入注册。我还有一个名为

的 CSV 文件

"Known file reg and names.csv"

我将其称为 "the doc",包括名称、地址和注册信息;如此处所示:

Bob Job GH58JBL 9, Henderson lane
Dan strobe  WK15HYO 12, Dominic Road
Alex Nail   VA11ZWU 6, Yake lane
Sam Jones   WX63GKP 273, Soomy Avenue
John English    WK64HRK 67, Wane Close

我有一个程序可以检测是否在名为 registration 的变量中输入了注册;与文档中的注册信息匹配。

import csv
registation=str(input("Please enter you registation plate."))
with open('Known file reg and names.csv', 'rt') as f:
    reader = csv.reader(f, delimiter=',')
    for row in reader:
        for field in row:
            if field == registation:
                print("We have found your reg in our database")

这有效,当输入与文档中匹配的注册时,程序将输出 "we have found your reg in our database"。

然后我有另一段代码 "supposed to" 将程序中的注册变量和文档中的匹配信息写入另一个包含特定人员详细信息的 csv 文件。

with open("saved database.csv", "w", newline="") as csvfile:
    w = csv.writer(csvfile)
    w.writerow([registation])
    w.writerow([field])

所以如果我输入 "WK15HYO" 程序应该比较文档中的信息和输入的注册变量,并重写应该是

的人员信息

WK15HYO Dan strobe, 12, Dominic Road

然而,情况并非如此,而是程序编写

67, Wane Close` and WK15HYO

。它不是在写 12、Dominic road 和 Dan strobe。 请给我一些关于我做错了什么以及如何解决问题的见解。

好的,有几件事。首先,您似乎完全没有必要遍历每一行中的字段。如果注册总是第二件事,你可以直接在 row[1] 寻找注册。当您将 field 写入 csv 文件时,您写入了分配给变量“field”的最后一个内容,在本例中是 csv 最后一行中的最后一个条目,67, Wane Close .下面的代码将专门搜索索引 1 处的注册,将完整信息保存为 user_info(或您选择的任何名称),然后结束迭代。

import csv
registation=str(input("Please enter you registation plate."))
with open('Known file reg and names.csv', 'rt') as f:
    reader = csv.reader(f, delimiter=',')
    for row in reader:
        if row[1] == registration:
            user_info = row
            break

当你打印这篇文章时,你现在有一些选择。您是否要将所有信息按姓名、注册、地址的顺序打印到一行?然后你可以简单地使用:

with open("saved database.csv", "w", newline="") as csvfile:
    w = csv.writer(csvfile)
    w.writerow(user_info)

如果您想做其他事情,那么您可以按照 desire.The 人名 user_info[0]、他们的注册 user_info[1] 和他们的地址 user_info[2].