如何在项目根目录下新建文件夹并将Pandas DataFrame保存为CSV文件?
Great question—this is a super common gotcha because Pandas' to_csv won’t automatically create missing folders for you. Let’s break down exactly how to make sure that CSV_Script_Results folder gets created in your project root, then save your DataFrame properly.
The key steps are:
- Reliably locate your project root directory (so the folder ends up in the right place, no matter where you run the script from)
- Create the target folder if it doesn’t exist
- Save the DataFrame to the correct path
Using Pathlib (Modern Python 3.4+)
This is the cleaner, more readable approach recommended for newer Python versions:
from pathlib import Path import pandas as pd # Get the absolute path to your script's directory (assumes script is in project root) project_root = Path(__file__).parent.resolve() # Define the path to the results folder results_folder = project_root / "CSV_Script_Results" # Create the folder (no error if it already exists) results_folder.mkdir(exist_ok=True) # Build the full path to your CSV file csv_file_path = results_folder / "tweepy_spaces.csv" # Save the DataFrame spaces_df.to_csv(csv_file_path, index=False)
Using os Module (Older Python Compatibility)
If you need to support Python versions before 3.4, use the os module instead:
import os import pandas as pd # Get the absolute path to your script's directory (project root) project_root = os.path.dirname(os.path.abspath(__file__)) # Define the results folder path results_folder = os.path.join(project_root, "CSV_Script_Results") # Create the folder (exist_ok=True prevents errors if folder already exists) os.makedirs(results_folder, exist_ok=True) # Build the full CSV file path csv_file_path = os.path.join(results_folder, "tweepy_spaces.csv") # Save the DataFrame spaces_df.to_csv(csv_file_path, index=False)
Adjusting for Scripts in Subfolders
If your script lives inside a subfolder (like src/your_script.py), tweak the project root path to move up one level:
- For Pathlib:
project_root = Path(__file__).parent.parent.resolve() - For os module:
project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
This ensures the CSV_Script_Results folder is always created directly in your project’s root directory, not a subfolder.
内容的提问来源于stack exchange,提问作者justin️

