私は、自分のファイルの説明である約7-8行上のcsvファイルを読んでいます。ヘッダー行を見つけた後に新しいcsvを作成するにはどうすればよいですか?
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にあると確信しています。これを行う最善の方法は何ですか?
ソリューション:
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
が、私は「R」と「W」の代わりに「RBを使用していたいくつかの理由のために、ありがとう"と" wb "とそれを更新しました。 –
@eleazaroliveraあなたはPython 3を使用していますか?はいの場合、バイナリモードのファイルを開くことによると、 'csv'モジュールは実際にはもう必要ないと思われます。 –