[英]How can I create a new csv after finding the header row?
我正在讀取一個csv文件,上面有大約7-8行,是對我的文件的描述。 我通過使用以下代碼進入第一列:
list_of_files = glob.glob('C:/payment_reports/*csv') # * means all if need specific format then *.csv
latest_file = max(list_of_files, key=os.path.getctime)
print (latest_file)
line_count = None
for row in csv.reader(open(latest_file)):
if row[0] == 'date/time':
print (row)
break
else:
print("{} not found".format('name'))
我要更正一行,因為打印的行是:
['date/time', 'settlement id', 'type', 'order id', 'sku', 'description', 'quantity', 'marketplace', 'fulfillment', 'order city', 'order state', 'order postal', 'product sales', 'shipping credits', 'gift wrap credits', 'promotional rebates', 'sales tax collected', 'Marketplace Facilitator Tax', 'selling fees', 'fba fees', 'other transaction fees', 'other', 'total']
現在,如何將列+之后的所有行另存為新的csv? 我有一個line_count,但是在嘗試使用新變量之前,我確定在csv中有一些使用行索引的函數,可以用來簡化事情。 你們建議什么是最好的方法?
解決方案:謝謝@bruno desthuilliers
list_of_files = glob.glob('C:/payment_reports/*csv') # * means all if need specific format then *.csv
latest_file = max(list_of_files, key=os.path.getctime)
print (latest_file)
with open(latest_file, "r") as infile:
reader = csv.reader(infile)
for row in reader:
if row[0] == 'date/time':
print (row)
break
else:
print("{} not found".format('name'))
break
with open("C:/test.csv", "w") as outfile:
writer = csv.writer(outfile)
writer.writerow(row) # headers
writer.writerows(reader) # remaining rows
csv.reader
是一個迭代器。 每次調用.next
時,它都會從csv中讀取一行。
這是文檔: http : //docs.python.org/2/library/csv.html 。
實際上,迭代器對象可以從太大而無法一次讀取所有數據的源中返回值。 將for循環與迭代器配合使用,每次在循環中都有效地調用.next
。 希望這可以幫助?
找到標頭行后,您可以將其寫出,並將其余行寫到輸出文件中:
with open(latest_file, "rb") as infile:
reader = csv.reader(infile)
for row in reader:
if row[0] == 'date/time':
break
else:
print("{} not found".format('name'))
return
with open("path/to/new.csv", "wb") as outfile:
writer = csv.writer(outfile)
writer.writerow(row) # headers
writer.writerows(reader) # remaining rows
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.