当前位置:   article > 正文

【报错记录】Python文件读取时报错FileNotFoundError: [Errno 2] No such file or directory: ‘xxx‘_python filenotfounderror: [errno 2] no such file o

python filenotfounderror: [errno 2] no such file or directory:

使用Python读取文件时:

fh = open('mbox.txt')
  • 1

如果显示报错:
FileNotFoundError: [Errno 2] No such file or directory: 'mbox.txt'
可能和编辑器的工作区有关。
例如我使用的编辑器是VSCode,会以打开的整个文件夹Python为工作区,文件的路径默认相对工作区,而不是py文件所在的文件夹。
例如:报错时文件的分布为:

Python
└── Using Databases with Python
     ├── Week-1
     ├── Week-2
     │  └── 2.1.py
     │  └── mbox.txt
     ├── Week-3
     ├── Week-4
     └── Week-5
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

这时若要打开文件,应当填写文件相对于工作区的路径:

fh = open('Using Databases with Python/Week-2/mbox.txt')
  • 1

便不会再报错。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/964105
推荐阅读
相关标签
  

闽ICP备14008679号