从CSV中删除前导空格将导致插入空行和删除行

2024-06-11 07:42:57 发布

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

包含以下内容(注意第一行没有前导空格):

Test1@bigfoot.com
 Test11@bigfoot.com
 Test1111@bigfoot.com
 Test111ew@bigfoot.com
 Test12312@bigfoot.com
 Test1231321@bigfoot.com
 Test1342321@bigfoot.com
 ....
 481 total rows

下面的代码正确地删除了前导空格,但在每个字符串行之后插入一个空行,并且,在每次执行总列表时,都会以随机数目的行数截断。在

^{pr2}$

以及:

with open('list.csv') as infile:
    reader = csv.DictReader(infile)
    fieldnames = reader.fieldnames
    for row in reader:
        row.update({fieldname: value.strip() for (fieldname, value) in row.items()})

当第一行中的字段名是空的时,它就是假定的。在


Tags: csvincomforvalueinfilereaderrow
1条回答
网友
1楼 · 发布于 2024-06-11 07:42:57

这里有几个问题:

  • csv文件必须在python3中用newline=""以写模式打开,否则它会在windows上插入空白
  • 不要在行上使用strip而使用lstrip,否则它会删除行末尾的换行符。会混淆csv阅读器
  • 使用with上下文块,这样可以确保文件在退出块时是关闭的(最后应该处理随机丢失的行)

我的建议:

with open('list.csv','r') as csvfile, open('complete_list.csv','w',newline="") as csvfile1:  # newline="" to avoid blanks
    stripped = (row.lstrip() for row in csvfile)  # lstrip not strip
    reader = csv.reader(stripped,delimiter=' ')
    writer= csv.writer(csvfile1)
    writer.writerows(reader)   # don't overstrip: just write rows as-is

相关问题 更多 >