从列表中读取 csv 文件名并在脚本中使用它们

Reading csv file names from a list and using them in a script

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

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\Experimental02 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'

文件在文件夹里,建表的时候可以用,就是不知道为什么现在突然找不到文件了。

您在 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)

应该可以解决您的问题

我只是 运行 你的代码。我认为问题是你的 .csv 文件在文件夹 path 中,所以如果只使用文件名 scoring 而没有目录名 path,你将找不到这些文件。要解决此问题,您需要

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

在你的循环中。