为什么DictWriter不能在Dictreader实例中写入所有行? [英] Why is DictWriter not Writing all rows in my Dictreader instance?
问题描述
我是编码的新手,默认情况下是Python的新手,所以请原谅我的无知...我正在努力.
I'm new to coding and by default new to Python, so please excuse my ignorance...I'm working on it.
我正在尝试编写一些代码(Python 2.7),以从多个CSV文件中获取特定的标头并将其导出为单个文件.这是我的代码:
I am trying to write some code (Python 2.7) to take specific headers from multiple CSV files and export them as a single file. Here is my code:
import csv, os
path = 'C:/Test/'
for fn in os.listdir(path):
if ".csv" in fn:
with open(fn, 'rb') as f:
with open('C:/Test/fun/output.csv', 'wb') as fou:
reader = csv.DictReader(f, delimiter=",", quotechar="|")
writer = csv.DictWriter(fou, delimiter=",", quotechar="|", fieldnames= ['sku', 'stock.qty', 'stock.is_in_stock'], extrasaction='ignore')
headers = {}
for n in writer.fieldnames:
headers[n] = n
writer.writerow(headers)
for row in reader:
print row
writer.writerow(row)
elif ".csv" not in fn:
break
阅读器实例的打印请求似乎可以打印多个文件中的所有行.我正在测试具有已知行的3个文件.但是,DictWriter输出文件仅具有最后读取的文件中的行.对于我来说,如何打印行和写行并获得不同的结果只是没有意义.显然,我的DictWriter写得不正确,但是我看不到哪里.对大多数人来说可能很明显,但我感到困惑.
The print request for the reader instance seems to print all rows from multiple files. I am testing on 3 files with known rows. However, the DictWriter output file only has the rows from the last of the files read. It just doesn't make sense to me how I can print row and writerow and get different results. Obviously my DictWriter is incorrectly written but I do not see where. Probably obvious to most but I am puzzled.
推荐答案
您正在打开目标CSV文件,并为您阅读的每个匹配CSV文件清除.在'wb'
模式下打开文件每次都会清除该文件.
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.
此外,一旦找到不是CSV文件的文件名,就会跳出循环;您可能根本不想这样做;删除else
分支.
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:
with open('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:
with open(fn, 'rb') as f:
reader = csv.DictReader(f, delimiter=",", quotechar="|")
for row in reader:
print row
writer.writerow(row)
我使用了 DictWriter.writeheader()
方法将您的字段名称作为初始标头写入输出文件.
I used the DictWriter.writeheader()
method to write your fieldnames to the output file as an initial header.
这篇关于为什么DictWriter不能在Dictreader实例中写入所有行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!