試圖讀取多個csv文件並將其解析爲txt文件。能夠讀取csv並將修改後的內容寫入txt文件。但是,在檢查具有原始csv的輸出時,發現第一條記錄不寫入文本文件。跳過2行的python csv閱讀器
樣品輸入csv文件的
INDEX,STRING1,STRING2,NUMBER1,NUMER2,DATE
ABC,abc,bcd,123,321,01-FEB-2017
BCD,bcd,cde,231,432,01-FEB-2017
我的代碼:
file_list =[]
list_of_files = os.listdir(os.getcwd())
for each_file in list_of_files: #reading csv files from the folder#
if (each_file.startswith('report') and each_file.endswith('.csv')):
file_list.append(each_file)
print(each_file) #all ok here#
for f in file_list: #reading from list of files above#
with open (f, 'r') as fin:
reader=csv.reader(fin)
next(reader, None)
for row in csv.reader(fin):
#reading date and creating txt file for that date#
file_date=datetime.datetime.strptime(row[5],'%d-%b-%Y').strftime('%Y%m%d')
text_file = open("Report_for_"+file_date+".txt", "w")
#writing header for the output file#
text_file.write("<field0>,<date>,<field2>,<field3>,..."+"\n")
for row in csv.reader(fin):
if row[1] == 'abc' or row[1] == 'xyz':
ASCII=row[0]+','+file_date+','+row[2]+','+row[3]+','+row[4]+','+row[1]
text_file.write(ASCII +"\n")
print ("Processing for " +file_date)
text_file.close()
print("done....")
我以前next(reader, None)
忽略標題。但是我的代碼也跳過了所有csv文件的第一條記錄。即使經過反覆的反覆試驗,也無法確定我出錯的地方。
'如果行[1] == 'ABC' 或行[1] == 'xyz''可能成爲'如果行中的[1](' ABC」, 'XYZ')' – asongtoruin