本地CSV文件导入Python失败,两段代码均无法运行求排查原因
Hey there! Let's troubleshoot why your CSV import code isn't running properly. There are a few common issues that could be causing this—let's break them down:
Common Issues & Fixes
1. Incorrect File Path
Most of the time, this is the root cause. Your Python script is looking for chicago.csv in its current working directory, which might not be where the file actually lives.
First, check where your script is running:
import os print(os.getcwd()) # This prints the folder your script uses as its base
Compare this path to where your chicago.csv is stored. If they don't match, you have two options:
- Move the CSV file into the directory printed by
os.getcwd() - Use the full absolute path to the file in your
open()call. For example:# Windows example with open('C:/Users/YourUsername/Documents/chicago.csv') as chicago_data: # macOS/Linux example with open('/home/yourusername/documents/chicago.csv') as chicago_data:
2. File Encoding Problems
If your CSV contains special characters (like accents or non-English text), Python's default encoding might not handle it, leading to a UnicodeDecodeError.
Fix this by specifying the correct encoding when opening the file. Common encodings are utf-8 (most standard CSVs) or gbk (Windows-generated CSVs with Chinese characters):
with open('chicago.csv', encoding='utf-8') as chicago_data:
3. File Permissions or Locked File
If you get a PermissionError, it means either:
- Your script doesn't have read access to the CSV file
- The file is currently open in another program (like Excel), which locks it from being read by Python. Close the file in other apps and try again.
Modified Test Code
Here's a version of your code that includes path checking and error handling to rule out these issues:
import os import csv # First confirm the working directory print("Current working directory:", os.getcwd()) # Use absolute path and specify encoding file_path = "/full/path/to/chicago.csv" # Replace with your actual path try: with open(file_path, encoding='utf-8') as chicago_data: csvReader = csv.reader(chicago_data) for row in csvReader: print(row) except FileNotFoundError: print(f"Error: Couldn't find the file at {file_path}") except UnicodeDecodeError: print("Error: Encoding issue—try changing 'utf-8' to 'gbk' in the open() call") except Exception as e: print(f"Unexpected error: {e}")
If you share the exact error message you're getting, we can narrow this down even further!
内容的提问来源于stack exchange,提问作者Jasch

