使用pathlib读取同目录文件时触发Python FileNotFoundError的问题
Path('pi_digits.txt')找不到同目录文件,但指定相对路径可行 我正在学习Eric Matthes的《Python Crash Course》,尝试读取同目录下的pi_digits.txt文件时遇到FileNotFoundError,代码如下:
from pathlib import Path # 指定文件路径 path = Path('pi_digits.txt') # 读取并打印文件内容 contents = path.read_text() print(contents)
错误信息:
Traceback (most recent call last): File "c:\Users\username\python_work\files_and_exceptions\file_reader.py", line 8, in <module> contents = path.read_text() File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.2032.0_x64__qbz5n2kfra8p0\Lib\pathlib.py", line 1058, in read_text with self.open(mode='r', encoding=encoding, errors=errors) as f: File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.2032.0_x64__qbz5n2kfra8p0\Lib\pathlib.py", line 1044, in open return io.open(self, mode, buffering, encoding, errors, newline) FileNotFoundError: [Errno 2] No such file or directory: 'pi_digits.txt'
我确认文件和脚本在同一目录(c:\Users\username\python_work\files_and_exceptions\),文件名正确、权限也没问题,但只有指定path = Path('files_and_exceptions/pi_digits.txt')才能正常运行,想知道直接用文件名失败的原因。
原因分析
核心问题是Python的当前工作目录和脚本所在目录不一致。
当你直接使用Path('pi_digits.txt')时,Python会在当前工作目录(也就是你启动Python时所在的目录)下查找文件,而非脚本实际存放的目录。从错误信息里的脚本路径来看,你的脚本在files_and_exceptions子目录中,但运行脚本时的工作目录可能是上层的python_work目录(甚至其他路径)。
举个例子:如果你在c:\Users\username\python_work\目录下执行python files_and_exceptions/file_reader.py,此时当前工作目录是python_work,而文件在files_and_exceptions子目录里,自然找不到;但指定files_and_exceptions/pi_digits.txt时,是基于当前工作目录的相对路径,所以能成功定位文件。
书中代码能生效,是因为作者运行脚本时的工作目录就是脚本所在的目录(比如先进入files_and_exceptions目录,再执行python file_reader.py)。
解决方法
方法1:切换到脚本所在目录再运行脚本
打开终端/命令行,先切换到脚本所在路径:
cd c:\Users\username\python_work\files_and_exceptions
然后运行脚本:
python file_reader.py
方法2:基于脚本目录构建文件路径(推荐)
这种方式能让脚本不受当前工作目录影响,无论从哪里启动都能找到文件,修改代码如下:
from pathlib import Path # 获取当前脚本所在的目录 script_dir = Path(__file__).parent # 拼接目标文件的完整路径 path = script_dir / 'pi_digits.txt' contents = path.read_text() print(contents)
__file__会返回当前脚本的完整路径,.parent获取它所在的目录,再用/运算符拼接文件名,就能确保路径始终正确。
内容的提问来源于stack exchange,提问作者Perspicacious Coder

