从csv中删除行(Python)

2024-09-21 11:34:20 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我试图创建一个函数,根据参数给定的名称从csv中删除一行

原始文件:

Janet,5,cats
Wilson,67,dogs
Karen,8,mice
John,12,birds

我的代码:

csv_remove("Karen")

预期文件:

Janet,5,cats
Wilson,67,dogs
John,12,birds

然而,当我执行代码时,到处都会出现奇怪的换行符

Janet,5,cats

Wilson,67,dogs

John,12,birds


以下是完整的代码:

def csv_remove(name):
    element_list = []
    with open(csv_path, 'r') as j:
        csv_file = csv.reader(j)
        for row in csv_file:
            element_list.append(row)
            if row[0] == name:
                element_list.remove(row)
    with open(csv_path, 'w') as j:
        csv_file = csv.writer(j)
        csv_file.writerows(element_list)

csv_remove("Karen")

Tags: 文件csv代码elementjohnremovelistfile
1条回答
网友
1楼 · 发布于 2024-09-21 11:34:20

阅读文档。使用csv模块打开文件进行写入时,您需要 供应newline=""

资料来源:https://docs.python.org/3/library/csv.html#csv.writer

csv.writer(csvfile, dialect='excel', **fmtparams)
Return a writer object responsible for converting the user’s data into delimited strings on the given file-like object. csvfile can be any object with a write() method. If csvfile is a file object, it should be opened with newline=''

csv模块本身处理换行符。如果您没有为打开的文件指定newline='',它会弄乱行尾,最后会出现空行

相关问题 更多 >

    热门问题