Python导入CSV文件报错求助:OSError初始化文件失败
Hey there! Let's work through this CSV import issue together—since you're new to Python, I'll break down the most common fixes step by step:
1. Double-check your file path and filename
- First, make sure the folders
Foldername1andFoldername2actually exist on your D: drive. Typos in folder or filenames are super easy to miss! - Verify the file is really named
data.csv. Windows often hides file extensions by default, so it might actually bedata.csv.txtwithout you realizing it. To check this, enable "File name extensions" in the Windows File Explorer view tab. - For testing, try moving the CSV file to a simpler path like
D:\data.csvand update your code to use that—this rules out issues with nested folders.
2. Check file locks and permissions
- Is the
data.csvfile open in another program (like Excel or Notepad)? If so, close it—pandas can't read files that are already locked by another app. - Ensure you have read permissions for the folder containing the CSV. If it's in a restricted directory (like Program Files), try copying the file to your desktop or Documents folder and importing from there instead.
3. Try reading via a file object
Sometimes direct path references can have hidden issues. Instead, open the file with Python's built-in open() function first, then pass it to pd.read_csv():
with open(r"D:\Foldername1\Foldername2\data.csv", 'r') as file: train1 = pd.read_csv(file)
If this still errors, it'll help narrow down whether the problem is with the path or the file itself.
4. Specify the file encoding
CSV files don't always use the default UTF-8 encoding. If your file was saved with a different encoding (like GBK, common for Chinese text, or UTF-16), try explicitly setting the encoding parameter:
# Try GBK first for Chinese-language files train1 = pd.read_csv(r"D:\Foldername1\Foldername2\data.csv", encoding='gbk') # Or try UTF-8 with BOM if the file has a byte order mark train1 = pd.read_csv(r"D:\Foldername1\Foldername2\data.csv", encoding='utf-8-sig')
Give these steps a shot—one of them should get you past that OSError!
内容的提问来源于stack exchange,提问作者zaaariina

