Python读取Excel文件遇FileNotFoundError问题求助
Let's break down the issues you're facing step by step—there are a couple of straightforward fixes here:
1. Fix the File Extension Typo
Looking at the error message, your file path ends with example1.xlxs—that's a simple typo! The correct file extension for modern Excel files is xlsx (note the order: x-l-s-x, not x-l-x-s). This is an extremely common mistake that breaks file lookup, even if the rest of your path is correct.
2. Correct Your File Path Formatting
The error shows the path being searched is \\Users\\Alex\\Documents\\Python\\Übung\\example1.xlxs—it’s missing the leading C: drive letter. While you mentioned using an absolute path, escape character handling in Python might have messed up the path parsing. To avoid this headache entirely, use a raw string for your path by prefixing it with r:
import openpyxl # Raw string treats backslashes as literal characters wb = openpyxl.load_workbook(r"C:\Users\Alex\Documents\Python\Übung\example1.xlsx")
This ensures Python doesn’t interpret backslashes as escape sequences, which often causes path truncation or misinterpretation.
3. Replace the Deprecated Worksheet Method
On top of the file path issue, wb.get_sheet_by_name() is deprecated in newer versions of openpyxl. Use these updated approaches instead:
- To list all available sheet names in your workbook:
print(wb.sheetnames) # Outputs all sheet names for reference - To directly access a specific sheet:
target_sheet = wb["Sheet1"] # Replace "Sheet1" with your actual sheet name
Corrected Full Code Example
import openpyxl # Load workbook with fixed path and extension wb = openpyxl.load_workbook(r"C:\Users\Alex\Documents\Python\Übung\example1.xlsx") # Confirm available sheets print("Available worksheets:", wb.sheetnames) # Access your target sheet sheet = wb["YourSheetName"] # Update with your sheet's name
Double-check that the file exists at the corrected path with the proper .xlsx extension, and this should resolve the FileNotFoundError.
内容的提问来源于stack exchange,提问作者Alexander Thiem

