python - 更改 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'
解决方案
这应该会有所帮助。
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
推荐阅读
- java - How to calculate String Buffer capacity?
- c - Visual C 中除以零异常处理
- networking - 连接“网络不可达”VPS Centos
- api - Retrofit 2 获取数据到 Listview Viewholder 模式,java.util.ArrayList.size 上的空指针异常
- opennms - OpenNMS - 监控 VPN 隧道流量
- php - 如何检查数据库 CodeIgniter 中的数组以及它们是否不存在添加它们
- swift - 忽略标志指针 0x10ef76ec0 的 RegisterValidateFunction():在 Xcode 中的该地址处找不到标志
- html - 对象未正确调整大小
- java - 将文本文件中的值存储到java中的数组中
- django - 模型序列化器销毁方法