首页 > 解决方案 > 更改 CSV 列中的数据格式

问题描述

我正在尝试将 CSV 文件中的日期格式 (DD-MMM-YY) 更改为 (YYYY-MM-DD)。

它的抛出错误。

import csv
from datetime import datetime

f1 = open ("D:\\bio.csv","r") # open input file for reading

with open('D:\\mm.csv', 'wb') as f: # output csv file
    writer = csv.writer(f)
    with open('D:\\bio.csv','r') as csvfile: # input csv file
        reader = csv.reader(csvfile, delimiter=',')
        next(reader, None)
        for row in reader:
            dater = row[2]
            #print (dater)
            my_date = datetime.strptime(dater, '%d-%b-%Y')

            kr = (my_date.date())

            row[2] = kr


            data = [["Symbol","Series","Date","Prev Close","Open Price","High Price","Low Price","Last Price","Close Price","Average Price","Total Traded Quantity","Turnover","No. of Trades","Deliverable Qty","% Dly Qt to Traded Qty"],row]

            writer.writerow(data)

f1.close()

CSV 样本

Symbol,Series,Date,Prev Close,Open Price,High Price,Low Price,Last Price,Close Price,Average Price,Total Traded Quantity,Turnover,No. of Trades,Deliverable Qty,% Dly Qt to Traded Qty
BIOCON,EQ,21-Jul-17,402.6,403,409.55,393.2,399,400.25,401.52,3032146,1217472594,39314,321923,10.62
BIOCON,EQ,24-Jul-17,400.25,399,405.9,396.1,399.6,399,401.25,2090835,838941962.6,25520,392951,18.79

一次又一次地尝试以多种方式获取输出,最终导致相同的错误。

错误:

Traceback (most recent call last):
  File "C:/Users/admin/PycharmProjects/P1/n.py", line 23, in <module>
    writer.writerow(data)
TypeError: a bytes-like object is required, not 'str'

标签: pythonpython-3.x

解决方案


这应该会有所帮助。

import csv
from datetime import datetime

with open(filename, "rU") as infile, open(filename2, "wb") as outfile:
    reader = csv.reader(infile)
    writer = csv.writer(outfile)
    writer.writerow(next(reader))   #Write Header
    result = []
    for line in reader:        #Iterate each line 
        temp = line
        temp[2] = datetime.strptime(temp[2], '%d-%b-%y').strftime("%Y-%m-%d")    #Update date format
        writer.writerow(temp)   #Write file

输出:

Symbol,Series,Date,Prev Close,Open Price,High Price,Low Price,Last Price,Close Price,Average Price,Total Traded Quantity,Turnover,No. of Trades,Deliverable Qty,% Dly Qt to Traded Qty
BIOCON,EQ,2017-07-21,402.6,403,409.55,393.2,399,400.25,401.52,3032146,1217472594,39314,321923,10.62
BIOCON,EQ,2017-07-24,400.25,399,405.9,396.1,399.6,399,401.25,2090835,838941962.6,25520,392951,18.79

推荐阅读