python - 尝试打开文件以在 Python 3 中读取时出现 FileNotFoundError
问题描述
我正在使用 OS 模块打开一个文件进行读取,但我收到了 FileNotFoundError。
我在尝试着
- 查找给定子目录中包含单词“mda”的所有文件
- 对于这些文件中的每一个,在两个“_”之后获取文件名中的字符串(表示称为 SIC 的特定代码)
- 打开该文件进行阅读
- 稍后将写入主文件以进行一些 Mapreduce 处理
当我尝试打开时,出现以下错误:
File "parse_mda_SIC.py", line 16, in <module>
f = open(file, 'r')
FileNotFoundError: [Errno 2] No such file or directory:
'mda_3357_2017-03-08_1000230_000143774917004005__3357.txt'
我怀疑问题出在“文件”变量或它是一个目录下的事实,但混淆了为什么当我使用操作系统来解决该较低目录时会发生这种情况。
我有以下代码:
working_dir = "data/"
for file in os.listdir(working_dir):
if (file.find("mda") != -1):
SIC = re.findall("__(\d+)", file)
f = open(file, 'r')
我希望能够毫无问题地打开文件,然后从数据中创建我的列表。谢谢你的帮助。
解决方案
这应该适合你。您需要附加该目录,因为它仅将其视为代码顶部的文件名,并且只会在您的代码所在的目录中查找该文件名。
for file in os.listdir(working_dir):
if (file.find("mda") != -1):
SIC = re.findall("__(\d+)", file)
f = open(os.path.join(working_dir, file), 'r')
此外,使用上下文管理器打开文件也是一个好习惯,with
因为它会在不再需要文件时处理关闭文件:
for file in os.listdir(working_dir):
if (file.find("mda") != -1):
SIC = re.findall("__(\d+)", file)
with open(os.path.join(working_dir, file), 'r') as f:
# do stuff with f here
推荐阅读
- c - “mmap 教程”不正确,还是 GCC 编译错误?
- typescript - 使用打字稿时“不支持 ES Module [...] 的 require()”
- django - 即使对于第一次使用 Djoser 和 DRF 的用户来说也是陈旧的令牌
- r - R [Shiny] 如何使用 deSolve 和 Shiny 将辅助函数实现到动态模型中
- spring-boot - 需要设置一个配置文件,让 Flyway 在重新启动时清理数据库
- javascript - 网络图未使用 js_on_change 更新 Bokeh 上的 Select 小部件
- javascript - 无论鼠标在哪里都可以滚动内容?
- swift - 我的图像如何在 Swift 中占据所有按钮的大小
- c++ - 创建一个启动非激活的无模式对话框 (MFC)
- c++ - 使用 __event 在 C++ 中处理事件