更改CSV列中的数据格式

时间:2018-08-01 18:33:48

标签: python python-3.x

我正在尝试将CS​​V文件中的日期格式(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'

2 个答案:

答案 0 :(得分:1)

这应该有帮助。

parameter

输出:

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

答案 1 :(得分:1)

不要以二进制模式打开文件(不带b标志打开文件):

with open('data_out.csv', 'w') as f: # output csv file

完整的来源(请注意,您可以同时使用多个open(),而且我在您的strptime中将%Y更改为%y):

import csv
from datetime import datetime

with open ("data.csv","r") as f1, open('data_out.csv', 'w') as f: # output csv file
    writer = csv.writer(f)
    with open('data.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(row)

文件输出将变为:

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