Why Is Dictwriter Not Writing All Rows In My Dictreader Instance?
I'm new to coding and by default new to Python, so please excuse my ignorance...I'm working on it. I am trying to write some code (Python 2.7) to take specific headers from multipl
Solution 1:
You are opening your target CSV file and clearing it for each matching CSV file you read. Opening the file in 'wb'
mode clears the file each time.
Moreover, you break out of the loop as soon as you find a filename that is not a CSV file; you probably didn't want to do that at all; remove the else
branch there.
Open the file just once, and continue to use it while looping over the directory, instead:
withopen('C:/Test/fun/output.csv', 'wb') as fou:
writer = csv.DictWriter(fou, delimiter=",", quotechar="|", fieldnames= ['sku', 'stock.qty', 'stock.is_in_stock'], extrasaction='ignore')
writer.writeheader()
for fn in os.listdir(path):
if".csv"in fn:
withopen(fn, 'rb') as f:
reader = csv.DictReader(f, delimiter=",", quotechar="|")
for row in reader:
print row
writer.writerow(row)
I used the DictWriter.writeheader()
method to write your fieldnames to the output file as an initial header.
Post a Comment for "Why Is Dictwriter Not Writing All Rows In My Dictreader Instance?"