使用字典python从不同的路径导入csv

时间:2019-03-19 14:16:54

标签: python

我正在尝试从其他路径导入CSV,以指示带有字典的指定路径。

import csv
import os
import pandas as pd

PATH = Path("../../Toxic-comment-classification")
PATH.mkdir(exist_ok=True)

args = {
    "data_dir": PATH,
}

class MultiLabelTextProcessor(DataProcessor):

    def __init__(self, data_dir):
        self.data_dir = data_dir
        self.labels = None


    def get_train_examples(self, data_dir, size=-1):
        filename = 'train.csv'
        data_df = pd.read_csv(os.path.join(data_dir, filename))
        return(data_df)

a = MultiLabelTextProcessor(args.values())
print(a.get_train_examples(a.data_dir))

但是,尝试运行时出现以下错误:

  

TypeError:预期的str,字节或os.PathLike对象,而不是dict_values

我了解args.values()给了我dict_object。我怎样才能将我的字典中的值作为字符串?

1 个答案:

答案 0 :(得分:2)

Obviously you are using Python 3. args.values() does not give you a dict object, but a dict_values, which the equivalent in Python 2 was a list. However, in your case, the list/dict_values has only one item, i.e. args.values() == [PATH] (sort of)

I bet you expect the args is a dict with only one entry so you want to extract that PATH content. You can simply do list(args.values())[0] on it. Or, in my opinion a better way, just use args['data_dir']

os.path.join(data_dir, filename) with data_dir a list or dict_values type and filename a string type is causing problem on your code.