【问题标题】:Reading csv file names from a list and using them in a script从列表中读取 csv 文件名并在脚本中使用它们
【发布时间】:2019-07-11 15:16:28
【问题描述】:

我有一个包含 csv 文件的文件夹,其中每个文件在开头都有一个字符串来标识游戏,最后有一个标签来标识该游戏中的哪个表。示例:

20020905_nyg_scoring.csv
20020905_nyg_team_stats.csv
20020908_buf_scoring.csv
20020908_buf_team_stats.csv

我编写了一个脚本,该脚本通过文件名的第一部分将 csv 文件配对到一个字典中,然后将该字典转换为一个列表。我想读取文件名对并一起对每一对执行数据帧整形。最终,我会将配对文件中的数据连接到单个数据帧中(连接不是我的问题)。

import numpy as np
import pandas as pd
import os

game_list = {}
path = r'C:\Users\jobon\Documents\New NFL Stats\Experimental\2002 Game Logs'
for file in os.listdir(path):
    game_pairing = game_list.get(file[:12],[])
    game_pairing.append(file)
    game_list[file[:12]] = game_pairing

game_pairs = []
for game, stats in game_list.items():
    game_pairs.append(stats)

for scoring, team_stats in game_pairs:
    for file in os.listdir(path):
        df1 = pd.read_csv(scoring, header = 0, index_col = 0)
        df1.drop(['Detail', 'Quarter', 'Time', 'Tm'], axis = 1, inplace = True)
        ...more shaping...

我希望以我可以连接的每对游戏文件生成的最终数据帧集结束。

我得到了

FileNotFoundError                         Traceback (most recent call last)
<ipython-input-37-fb1d4aa9f003> in <module>
     18 for scoring, team_stats in game_pairs:
     19     for file in os.listdir(path):
---> 20         df1 = pd.read_csv(scoring, header = 0, index_col = 0)
     21         #df1.drop(['Detail', 'Quarter', 'Time', 'Tm'], axis = 1, inplace = True)
     22         print(df1)

FileNotFoundError: [Errno 2] File b'20020905_nyg_scoring.csv' does not exist: b'20020905_nyg_scoring.csv'

文件在文件夹中,可以用来建列表,但是不知道为什么现在突然找不到文件了。

【问题讨论】:

  • 尝试:df1 = pd.read_csv(scoring.decode("utf-8"), header = 0, index_col = 0) 并得到:AttributeError:'str' 对象没有属性'decode' 所以我尝试:df1 = pd.read_csv(codecs.decode(scoring, encoding='ASCII', errors='strict'), header = 0, index_col = 0) 并得到:TypeError:使用'utf-8'编解码器解码失败( TypeError:需要一个类似字节的对象,而不是'str')

标签: python csv ipython filenames


【解决方案1】:

我刚刚运行了您的代码。我认为问题在于您的.csv 文件位于path 文件夹中,因此如果仅使用文件名scoring 而没有目录名称path,则无法找到这些文件。要解决此问题,您需要

scoring = os.path.join(path, scoring)

在你的循环中。

【讨论】:

    【解决方案2】:

    似乎您在 read_csv 方法中传递的第一个变量不是字符串文字,而是字节文字。这就是错误提到文件 b'20020905_nyg_scoring.csv' 而不是'20020905_nyg_scoring.csv' 的原因。开头的 b 表示字节文字。

    变化

    df1 = pd.read_csv(scoring, header = 0, index_col = 0)
    

    到

    df1 = pd.read_csv(scoring.decode("utf-8"), header = 0, index_col = 0)
    

    应该解决你的问题

    【讨论】:

    • 尝试并得到:AttributeError: 'str' object has no attribute 'decode'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-12
    • 2019-08-03
    • 2017-02-19
    • 1970-01-01
    • 1970-01-01
    • 2015-06-26
    相关资源
    最近更新 更多