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

问题描述 投票:0回答:1

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

[email protected]
 [email protected]
 [email protected]
 [email protected]
 [email protected]
 [email protected]
 [email protected]
 ....
 481 total rows

以下正确删除前导空格,但在每个字符串行后面插入一个空行,AND,每次执行时,按行随机数截断总列表。

csvfile= open('list.csv','r')
csvfile1= open('complete_list.csv','w')
stripped = (row.strip() for row in csvfile)
reader = csv.reader(stripped,delimiter=' ')
writer= csv.writer(csvfile1)
for row in reader:
    writer.writerow([e.strip() for e in row])

和:

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()})

什么都不做,因为第一行被假定为fieldname,而实际上它只是......一行。

python python-3.x csv null whitespace
1个回答
1
投票

这里有几个问题:

  • 必须在python 3中使用newline=""以写入模式打开csv文件,否则它会在窗口中插入空格
  • 不要在线上使用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
© www.soinside.com 2019 - 2024. All rights reserved.