You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

读取文件指定路径时触发FileNotFoundError错误求助

Fixing FileNotFoundError: [Errno 2] No such file or directory: 'pprog.txt'

Alright, let's break down why you're hitting this error when specifying a file path, while another method works perfectly. Here are the most common issues and straightforward fixes:

1. Your relative path doesn't match the current working directory

When you use just 'pprog.txt', Python looks for the file in the current working directory (the folder your script is running from)—not necessarily the folder where your script file is saved.

  • To check what your current working directory is, run this quick snippet:
    import os
    print(os.getcwd())
    
  • Adjust the path based on where your file actually lives:
    • If the file is one folder above your working directory: '../pprog.txt'
    • If it's in a subfolder: './my_files/pprog.txt'
    • For absolute reliability, use an absolute path (no guesswork involved):
      # Linux/macOS example
      with open('/home/your_username/Documents/pprog.txt', 'r') as file:
          content = file.read()
      # Windows example (use forward slashes or double backslashes)
      with open('C:/Users/your_username/Documents/pprog.txt', 'r') as file:
          content = file.read()
      

2. Typos or case sensitivity got you

It's easy to misspell a filename, or overlook case differences that matter:

  • On Linux and macOS, filenames are case-sensitive: pprog.txtPPROG.txt
  • Even on Windows (case-insensitive by default), hidden file extensions can trick you—like saving a file as pprog.txt.txt without realizing it.

Double-check the exact filename in your file explorer, then copy-paste it directly into your code to avoid typos.

3. The file isn't where you think it is

Sometimes files get moved accidentally, or you saved them to a different folder than intended.

  • Manually navigate to the folder you expect the file to be in and confirm it's there.
  • Use command line tools to verify: ls (Linux/macOS) or dir (Windows) to list the directory contents.

4. Rare: Permission issues (though error usually differs)

If you’re sure the file exists but still get this error, double-check that your user account has access to the file or its parent folder. Note that this usually throws a PermissionError instead, but it’s worth ruling out if other fixes fail.

Work through these steps, and you’ll have your file reading code working consistently in no time.

内容的提问来源于stack exchange,提问作者Slumpe

火山引擎 最新活动