如何从使用python创建的csv文件中删除空行

时间:2016-08-19 08:19:13

标签: python csv

我们正在从一个大的csv文件创建一个子文件。子文件仅包含那些第一列的值为D1的行:

import csv
with open('input.csv', 'rb') as csvfile:

     reader = csv.reader(csvfile, delimiter='|', quotechar='|')

     writer1 = csv.writer(open('output.csv', 'w'), delimiter = ' ')

     for row in reader:
         a = row[0]
         row  =  '|'.join(row)
         if (a=='D1'):
                 writer1.writerow(row)

此代码提供了两个问题:

  1. 新csv文件中的每一行后面都有一个空行
  2. 每个单词之间都有额外的空格。所以,"你好"变为"H e l l o"

2 个答案:

答案 0 :(得分:1)

此代码运行良好:

import csv
with open('input.csv', 'rb') as csvfile:

     reader = csv.reader(csvfile, delimiter='|', quotechar='|')

     writer1 = csv.writer(open('output.csv', 'wb'), delimiter = '|')

     for row in reader:
         a = row[0]
         if (a=='D1'):
                 writer1.writerow(row)

感谢Pedru

答案 1 :(得分:0)

来自python csv docs ..

import csv
with open('eggs.csv', 'w', newline='') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=' ',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)
    spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
    spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])

所以看来你必须使用['Spam']列表spamwriter.writerow ...如果它不是列表,这个方法writerow正在从可迭代输入创建自己的列表,如下所示: / p>

>>> a = 'ala ma kota'
>>> list(a)
['a', 'l', 'a', ' ', 'm', 'a', ' ', 'k', 'o', 't', 'a']