csv ValueError:()中的回溯(最近的呼叫最后)< ipython-input-15-d27c936e2293>< module>

jk9hmnmh  于 2022-12-06  发布在  Python
关注(0)|答案(1)|浏览(114)

我尝试从csv文件读取数据,但出现以下错误:

ValueError                                Traceback (most recent call last)
<ipython-input-15-d27c936e2293> in <module>()
 11 for row in header:
 12     # row = [Date, Open, High, Low, Close, Volume, Adj. close]
---> 13     date = datetime.strptime(row[0], '%m/%d/%Y')
     14     open_price = float(row[1])
     15     high = float(row[2])

~/anaconda3/lib/python3.6/_strptime.py in _strptime_datetime(cls, data_string, format)
563     """Return a class cls instance based on the input string and the
564     format string."""
--> 565     tt, fraction = _strptime(data_string, format)
566     tzname, gmtoff = tt[-2:]
567     args = tt[:6] + (fraction,)

~/anaconda3/lib/python3.6/_strptime.py in _strptime(data_string, format)
360     if not found:
361         raise ValueError("time data %r does not match format %r" %
--> 362                          (data_string, format))
363     if len(data_string) != found.end():
364         raise ValueError("unconverted data remains: %s" %

ValueError: time data 'D' does not match format '%m/%d/%Y'

下面是我的代码:

import csv 
from datetime import datetime 

path ="google_stock_data.csv"
file = open (path, newline = '')
reader = csv.reader(file)

header = next (reader)

data = [] 
for row in header: 
# row = [Date, Open, High, Low, Close, Volume, Adj. close]
   date = datetime.strptime(row[0], '%m/%d/%Y')
   open_price = float(row[1])
   high = float(row[2])
   low = float(row[3])
   close = float(row[4])
   volume = float(row[5])
   adj_close = float(row[6])

data.append([date, open_price, high, low, close, volume, adj_close])

print(data[0])

注意:文件中的数据如下所示:

Date      Open        High        Low          Close      Volume      Adj Close

8/19/14 585.002622  587.342658  584.002627  586.862643  978600  586.862643
8/18/14 576.11258   584.512631  576.002598  582.162619  1284100 582.162619
8/15/14 577.862619  579.382595  570.522603  573.482626  1519100 573.482626
8/14/14 576.182596  577.902645  570.882599  574.652582  985400  574.652582

为什么会这样?数据没有被转换成正确的类型吗?请帮助。我该如何修复它?

  • 谢谢-谢谢
zazmityj

zazmityj1#

您的示例代码很接近,但存在一些问题:首先,for循环中有一个排印错误,它应该是

for row in reader:

其次,看起来datetime解析器不支持月份和日期不填零的日期格式。因此,使用dateutil.parser:

from dateutil.parser import parse
date = parse(row[0], dayfirst=False)

最后,csv不喜欢字段之间有多个空格,但是你可以定义自己的方言来解决这个问题:

csv.register_dialect('dataformat', delimiter=' ', skipinitialspace=True)
reader = csv.reader(file, dialect='dataformat')

skipinitialspace将占用字段之间的多余空格

相关问题