gpt4 book ai didi

python - 尝试打开文件以在 Python 3 中读取时出现 FileNotFoundError

转载 作者:太空宇宙 更新时间:2023-11-04 02:00:04 24 4
gpt4 key购买 nike

我正在使用 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'

我怀疑问题要么与"file"变量有关,要么是它在一个目录下,但我很困惑为什么当我使用操作系统来处理该较低目录时会发生这种情况。

我有以下代码:

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

关于python - 尝试打开文件以在 Python 3 中读取时出现 FileNotFoundError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55895254/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com