我正在使用OS模块打开文件进行读取,但出现FileNotFoundError。
我在尝试着
当我尝试打开时,出现以下错误:
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'
我怀疑问题出在“文件”变量还是它在一个目录下,但我为什么在使用OS寻址该较低目录时会发生这种情况,我感到困惑。
我有以下代码:
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句