从读取的csv文件中删除行结束符



我尝试了几次使用strip(),但我不能让它工作。我把那块剪掉了但每次我试着剪的时候错误或者什么都没做。排序很好,我只是想在写入新文件之前去掉换行符?

import sys, csv, operator
data = csv.reader(open('tickets.csv'),delimiter=',')
sortedlist = sorted(data, key=operator.itemgetter(6))
# 0 specifies according to first column we want to sort
#now write the sort result into new CSV file

with open("newfiles.csv", "w") as f:
#writablefile = csv.writer(f)
fileWriter = csv.writer(f, delimiter=',')
for row in sortedlist:
#print(row)
lst = (row)
fileWriter.writerow(lst)

在写入CSV文件时需要将newline=''添加到open()中。这在文档中有解释。如果没有它,你的文件可能每行都有一个空行。

import sys, csv, operator
data = csv.reader(open('tickets.csv'),delimiter=',')
header = next(data)
sortedlist = sorted(data, key=operator.itemgetter(6))
# 0 specifies according to first column we want to sort
#now write the sort result into a new CSV file
with open("newfiles.csv", "w", newline="") as f:
fileWriter = csv.writer(f)

fileWriter.writerow(header)     # keep the header at the top
fileWriter.writerows(sortedlist)

还需要在加载所有内容进行排序之前先读取标题行。这避免了它被排序。然后在编写排序输出CSV时可以单独输出。

如果您的tickets.csv文件包含空白行,您还需要删除它们。例如:

for row in sortedList:
if row:
fileWriter.writerow(row)

相关内容

  • 没有找到相关文章

最新更新