使用pd.read_csv读取BRK.B文件时出现FileNotFoundError异常排查
Ah, I’ve run into this exact issue before with tickers that include dots (like BRK.B or GOOG.L)! Let’s break down why this might be happening and fix it step by step.
Common Causes & Fixes
1. You’re Missing the .csv Extension (or Mismatching It)
It’s easy to overlook: if your file is actually named BRK.B.csv but your code is trying to load BRK.B (without the .csv), pandas will throw a FileNotFoundError. Even if you see "BRK.B" in your file explorer, many operating systems hide file extensions by default.
Quick Check:
Run this snippet to list every file in your stock_dfs folder—this will show you the exact filenames, including extensions:
import os print("All files in stock_dfs:", os.listdir("stock_dfs"))
Fix:
When constructing your file path, make sure to append .csv to the ticker:
import pandas as pd import os ticker = "BRK.B" file_path = os.path.join("stock_dfs", f"{ticker}.csv") if os.path.exists(file_path): df = pd.read_csv(file_path) print(f"Successfully loaded {ticker}!") else: print(f"File doesn't exist at: {file_path}")
2. Case Sensitivity Mismatch
If you’re on Linux or macOS, filenames are case-sensitive. For example, if your file is named brk.b.csv but your code uses BRK.B.csv, it won’t find the file. The os.listdir() snippet above will also reveal this mismatch.
Fix:
Either adjust your code to match the exact case of the filename, or rename the file to match your code’s ticker format.
3. Hidden Characters in the Filename
Sometimes filenames have invisible spaces or special characters (like trailing spaces) that you can’t see in file explorer. For example, the file might actually be named BRK.B .csv (note the space after the dot).
Fix:
Use the os.listdir() snippet to print the raw filenames—any hidden characters will show up here. You can then rename the file to remove them, or adjust your code to match the exact filename.
4. Path Concatenation Errors
If you’re manually building file paths (e.g., "stock_dfs/" + ticker + ".csv"), you might accidentally introduce issues with slashes or special characters. Using os.path.join() avoids this, as it handles OS-specific path separators automatically.
Best Practice:
Always use os.path.join() to construct file paths, especially when dealing with tickers that have special characters like dots:
file_path = os.path.join("stock_dfs", f"{ticker}.csv")
Final Troubleshooting Step
If none of the above works, run this code to iterate through all CSV files in your folder and load them—this will bypass any ticker-name mismatches entirely:
import pandas as pd import os folder_path = "stock_dfs" stock_data = {} for filename in os.listdir(folder_path): if filename.endswith(".csv"): # Extract the ticker by removing the .csv extension ticker = filename[:-4] try: df = pd.read_csv(os.path.join(folder_path, filename)) stock_data[ticker] = df print(f"Loaded {ticker} successfully") except Exception as e: print(f"Failed to load {filename}: {str(e)}")
This will load every valid CSV file in the folder, including BRK.B, and store them in a dictionary keyed by ticker.
内容的提问来源于stack exchange,提问作者Q. Wieber

