You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python读取CSV文件报错:文件未找到问题求助

Fixing "File Not Found" Error When Reading CSV with NumPy

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:28:00