Python错误:打开csv时需要str、bytes或os.PathLike对象

2024-04-20 09:28:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在运行以下python 3代码:

import os
import csv
import glob
import numpy as np
import collections


Prices = collections.namedtuple('Prices', field_names=['time', 'open', 'high', 'low', 'close', 'volume'])


def read_csv(file_name, sep=',', filter_data=True, fix_open_price=False):
    print("Reading", file_name)                 
    with open(file_name, 'rt', encoding='utf-8') as fd:
        reader = csv.reader(fd, delimiter=sep)
        x = next(reader)                      
        if '<OPEN>' not in x and sep == ',':  
            return read_csv(file_name, ';') 
        indices = [x.index(s) for s in ('<TIME>', '<OPEN>', '<HIGH>', '<LOW>', '<CLOSE>', '<VOL>')]
        t, o, h, l, c, v = [], [], [], [], [], []
        count_out = 0
        count_filter = 0
        count_fixed = 0
        prev_vals = None
        for row in reader:
            vals = list(map(float, [row[idx] for idx in indices]))
            if filter_data and all(map(lambda v: abs(v-vals[0]) < 1e-8, vals[:-1])):
                count_filter += 1
                continue

            to, po, ph, pl, pc, pv = vals

            # fix open price for current bar to match close price for the previous bar
            if fix_open_price and prev_vals is not None:
                ppo, pph, ppl, ppc, ppv = prev_vals
                if abs(po - ppc) > 1e-8:
                    count_fixed += 1
                    po = ppc
                    pl = min(pl, po)
                    ph = max(ph, po)
            count_out += 1
            t.append(to)
            o.append(po)
            c.append(pc)
            h.append(ph)
            l.append(pl)
            v.append(pv)
            prev_vals = vals
    print("Read done, got %d rows, %d filtered, %d open prices adjusted" % (count_filter + count_out, count_filter, count_fixed))
    return Prices(time=np.array(t, dtype=np.int),
                  open=np.array(o, dtype=np.float32),
                  high=np.array(h, dtype=np.float32),
                  low=np.array(l, dtype=np.float32),
                  close=np.array(c, dtype=np.float32),
                  volume=np.array(v, dtype=np.float32))

def prices_to_relative(prices):
    """   
    Convert prices to relative in respect to open price
    :param ochl: tuple with open, close, high, low     
    :return: tuple with open, rel_close, rel_high, rel_low
    """   
    assert isinstance(prices, Prices)            
    rh = (prices.high - prices.open) / prices.open
    rl = (prices.low - prices.open) / prices.open
    rc = (prices.close - prices.open) / prices.open
    tm = prices.time
    return Prices(time=tm, open=prices.open, high=rh, low=rl, close=rc, volume=prices.volume)


def load_relative(csv_file):
    return prices_to_relative(read_csv(csv_file))


def price_files(dir_name):
    result = []
    for path in glob.glob(os.path.join(dir_name, "*.csv")):
        result.append(path)
    return result


def load_year_data(year, basedir='data'):
    y = str(year)[-2:] 
    result = {}        
    for path in glob.glob(os.path.join(basedir, "*_%s*.csv" % y)):
        result[path] = load_relative(path)
    return result      


load_relative(read_csv('/home/darfeder/Downloads/9781838826994_Code/Chapter10/data/YNDX_150101_151231.csv'))

我得到一个错误:

TypeError: expected str, bytes or os.PathLike object, not Prices

加载的csv文件如下所示:

^{tb1}$

错误出现在“价格相对”函数中

堆栈跟踪:

--------------------------------------------------------------------------- TypeError Traceback (most recent call last) in 87 88 ---> 89 load_relative(read_csv('/home/darfeder/Downloads/9781838826994_Code/Chapter10/data/YNDX_150101_151231.csv'))

in load_relative(csv_file) 69 70 def load_relative(csv_file): ---> 71 return prices_to_relative(read_csv(csv_file)) 72 73

in read_csv(file_name, sep, filter_data, fix_open_price) 11 def read_csv(file_name, sep=',', filter_data=True, fix_open_price=False): 12 print("Reading", file_name) ---> 13 with open(file_name, 'rt', encoding='utf-8') as fd: 14 reader = csv.reader(fd, delimiter=sep) 15 x = next(reader)

TypeError: expected str, bytes or os.PathLike object, not Prices


Tags: csvnameinreaddatareturncountnp
1条回答
网友
1楼 · 发布于 2024-04-20 09:28:15

您的代码似乎很奇怪-当我希望只看到一个调用时,有几个调用read_csv,例如:

大体上:

load_relative(read_csv('/home/darfeder/Downloads/9781838826994_Code/Chapter10/data/YNDX_150101_151231.csv'))

在load_relative中:

return prices_to_relative(read_csv(csv_file))

在read_csv中,递归调用?(我想这可能还可以,适合使用;作为CSV分隔符):

return read_csv(file_name, ';') 

我认为问题是第一个:传递文件名而不是读取文件的结果,因此将其更改为:

load_relative('/home/darfeder/Downloads/9781838826994_Code/Chapter10/data/YNDX_150101_151231.csv')

此外,您还应打开csv文件而不指定“rt”,并根据文档示例https://docs.python.org/3/library/csv.html指定换行符='',因此更改:

with open(file_name, 'rt', encoding='utf-8') as fd:

致:

with open(file_name, newline='', encoding='utf-8') as fd:

由于您没有提供示例数据,我没有办法对此进行测试-希望这些建议能够解决问题

相关问题 更多 >