Python读取CSV文件报错:文件未找到问题求助
Hey there, let's troubleshoot why your rail length data file isn't being recognized by Python—even after moving it to the D drive. Here are the most likely issues and fixes:
1. Escape Character Messing Up Your Path
On Windows, the backslash \ in file paths is an escape character (like \r gets interpreted as a carriage return). That means your path 'd:\rail-length-km-at-end-of-year' isn't being read correctly by Python.
Fix it in one of three ways:
- Use double backslashes:
'd:\\rail-length-km-at-end-of-year.csv' - Use a raw string (prefix with
r):r'd:\rail-length-km-at-end-of-year.csv' - Use forward slashes instead:
'd:/rail-length-km-at-end-of-year.csv'
2. Missing File Extension
Did you forget to add the .csv suffix? If your actual file is named rail-length-km-at-end-of-year.csv (most CSV files have this extension), your code is looking for a file with no extension at all—hence the "not found" error.
3. Verify the Exact File Path
Double-check that you're using the correct filename and path. You can:
- Right-click the CSV file → Go to Properties → Copy the full path from the "Location" field
- Paste that exact path into your code (making sure to handle escape characters as mentioned above)
Modified Working Code
Here's your code with the path fixed (using raw string and adding .csv—adjust if your filename has a different extension):
import numpy as np import matplotlib.pyplot as plt title = "Length of rails" titlelen = len(title) print("{:*^{titlelen}}".format(title, titlelen=titlelen+6)) print() # Fixed path using raw string and adding .csv extension data = np.genfromtxt(r'd:\rail-length-km-at-end-of-year.csv', skip_header=1, dtype=[('year','U10'),('rail_type','U50'), ('length','i8')], delimiter=",", missing_values=['na','-'], filling_values=[0]) x_public = data[data['rail_type']=='public sector']['year'] y_public = data[data['rail_type']=='public sector']['length'] x_private = data[data['rail_type']=='Private Sector']['year'] y_private = data[data['rail_type']=='Private Sector']['length'] fig = plt.figure() ax1 = fig.add_subplot(111) ax1.plot(x_public, y_public, c='b', label='Public Sector') ax1.plot(x_private,y_private, c='r', label='Private Sector') plt.ylabel('rail length') plt.legend(loc='upper left') plt.show()
Quick Debug Tip
If you're still stuck, run this to check Python's current working directory—maybe it's looking in the wrong place by default:
import os print(os.getcwd())
内容的提问来源于stack exchange,提问作者Askar Mujhib

