简体   繁体   English

如何从CSV文件读取单独的行?

[英]How can I read individual lines from a CSV file?

At the moment I've got this function: 目前,我具有以下功能:

def writer(file_name)
    open_file = open(file_name,"r+", newline='')
    csv_output = csv.writer(open_file) 
    csv_output.writerow(student)
    open_file.close()

where student is: student在哪里:

"string_1","string_2",int

I'm looking to read through the file first and check if the "string_1" that I'm writing matches any of the "string_1" s already written, but I can't find a built-in function that lets me read each line and store it as a list. 我想先通读文件,并检查我正在编写的"string_1"是否与任何已写入的"string_1"匹配,但找不到能够让我读取每一行的内置函数并将其存储为列表。

First, you have to open the file for reading, go through the file line by line and return, if "string_1" is found: 首先,如果找到“ string_1”,则必须打开文件进行读取,逐行浏览并返回:

def append_student(file_name, student)
    with open(file_name, "r") as f:
        for line in csv.reader(f):
            if line[0] == student[0]:
                return
    with open(file_name, "a") as f:
        csv.writer(f).writerow(student)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM