使用以下内容(注意第一行没有前导空格):
Test1@bigfoot.com
Test11@bigfoot.com
Test1111@bigfoot.com
Test111ew@bigfoot.com
Test12312@bigfoot.com
Test1231321@bigfoot.com
Test1342321@bigfoot.com
....
481 total rows
以下正确删除了前导空格,但在每个字符串行后插入一个空行,并且每次执行时,截断总行列表的随机行数。
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,实际上它只是......一行。
答案 0 :(得分:1)
这里有几个问题:
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