文件与代码同目录仍触发FileNotFoundError问题求助
解决FileNotFoundError:文件与脚本同目录但仍无法找到的问题
针对你遇到的FileNotFoundError: [Errno 2] No such file or directory: 'breast_cancer.txt'问题,即使文件和pre_process_data.py在同一目录,也可能是以下几个原因导致的,对应解决思路如下:
1. 当前工作目录不是脚本所在目录
运行脚本时,Python的**当前工作目录(CWD)**不一定是脚本文件所在的目录。比如你在终端中从~/projects目录运行python data/pre_process_data.py,此时CWD是~/projects,而不是~/projects/data,代码中直接用文件名打开会在CWD里查找,自然找不到目标文件。
解决方法:
通过脚本所在的绝对路径拼接文件名,确保无论在哪里运行都能定位到文件。修改代码如下:
import re import os # 获取脚本所在目录的绝对路径 script_dir = os.path.dirname(os.path.abspath(__file__)) cancer_text = ['breast_cancer.txt', 'colorectal_cancer.txt', 'lung_cancer.txt', 'prostate_cancer.txt', 'skin_cancer.txt'] for file in cancer_text: # 拼接文件的绝对路径 file_path = os.path.join(script_dir, file) with open(file_path, 'r') as f: text = f.read() # 注意:with语句会自动关闭文件,不需要手动调用f.close() with open(file_path, 'w') as f: print('pre-processing the file {}'.format(file)) text = re.sub("[!@#$+%*:()'-]", ' ', text) text = text.lower() f.write(text)
另外,你的代码里手动调用了f.close(),这是多余的——with open(...)上下文管理器会在代码块结束后自动关闭文件,建议去掉。
2. 文件名拼写/大小写不匹配
检查实际文件名和代码中的字符串是否完全一致:
- 注意大小写:Linux/macOS系统区分文件名大小写,比如实际文件是
Breast_Cancer.txt,代码里写breast_cancer.txt会找不到;Windows系统不区分,但也建议保持一致。 - 检查后缀名:比如实际文件是
breast_cancer.txt.txt(被系统隐藏了后缀),看起来是breast_cancer.txt,但实际文件名不同。
3. 文件实际不存在或被移动
直接在脚本所在目录下,用终端命令确认文件是否存在:
- Linux/macOS:运行
ls查看目录内容 - Windows:运行
dir查看目录内容
如果文件确实不存在,需要确认文件是否被误删除、移动,或者是否正确放置到了脚本目录下。
内容的提问来源于stack exchange,提问作者Paul
相关产品推荐
相关产品推荐

