CSV - .append和.difference问题以及空行

时间:2014-12-10 14:02:41

标签: python csv

如果有人可以提供帮助,我的代码会遇到一些奇怪的问题。

import re
import csv
#import pdb
#pdb.set_trace()

# Variables
newStock = "newStock.csv" #csv file with list of new stock
allActive = "allActive.csv" #csv file with list of all active
skusToCheck= []
totalNewProducts = 0
i = 0

found = []
leftOvers =[]

# Program Start - Open first csv
a = open(newStock)
csv_f = csv.reader(a)

# Copy each row into array thingy
for row in csv_f:
    skusToCheck.append(row[0])

# Get length of array
totalNewProducts = len(skusToCheck)

# Open second csv
b = open(allActive)
csv_f = csv.reader(b)

# Open blank csv file to write to
csvWriter = csv.writer(open('writeToMe.csv', 'w'), delimiter=',',
                       quotechar='|', quoting=csv.QUOTE_MINIMAL)
csvWriter2 = csv.writer(open('found.csv', 'w'), delimiter=',',
                        quotechar='|', quoting=csv.QUOTE_MINIMAL)

# Check first value in first row,first file against
# each entry in 2nd row in second file
with open(allActive, 'rt') as b:
    reader = csv.reader(b, delimiter=",")
    for row in reader:
        if len(row) > 1:
            for sku in skusToCheck:
                if sku == row[1]:
                    found.append(sku)
                    csvWriter.writerow(row) # write matching row to new file
                    break

# Create sets to compare
found1 = set(found)
skusToCheck1 = set(skusToCheck)

# Populate leftovers with the leftovers
leftOvers.append(skusToCheck1.difference(found1))

# write leftovers to a new file
csvWriter2.writerow(leftOvers)

# Output to screen results
print("-" * 80)
print('Added: ', len(found))
print(" ")
print(found)
print(" ")
print("-" * 80)
print('Not Found: ', len(leftOvers))
print(" ")
print(leftOvers[])
print(" ")
print("-" * 80)

问题:

  1. csvWriter.writerow(第46行)
    预期:将行输出到csv文件,一行一行,行之间没有空格。
    实际:输出我要求的所有数据,但在每个条目之间添加一个空行。

  2. leftOvers.append(skusToCheck1.difference(found1))(第54行)
    预期:将两个列表之间的差异添加到剩菜中 实际:将列表追加到一个单元格。

1 个答案:

答案 0 :(得分:0)

听起来像是在窗户上

尝试在写入语句中的delimiter =','之后添加lineterminator ='\ n'

即:

with open('c:/some.csv', "w") as fp:
    a = csv.writer(fp, delimiter=',', lineterminator='\n')
    data = ['some','data']
    a.writerow(data)

如果你想附加到文件,请使用“a”代替“w”进行写入。