因此,我试图创建一个函数,根据参数给定的名称从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")
阅读文档。使用csv模块打开文件进行写入时,您需要 供应
newline=""
:资料来源:https://docs.python.org/3/library/csv.html#csv.writer
csv模块本身处理换行符。如果您没有为打开的文件指定
newline=''
,它会弄乱行尾,最后会出现空行相关问题 更多 >
编程相关推荐