Python open: FileNotFoundError: [Errno 2] No such file or directory
程序员文章站
2022-07-15 17:00:35
...
使用python函数open创建txt的时候:
with open(os.path.join(pwd_p, "train_mask.txt"), 'w') as f:
for file in masks:
f.write(file)
报错:
FileNotFoundError: [Errno 2] No such file or directory: ‘Volumes/WorkPlace/seg_pic/train_mask.txt’
原因:
使用open函数打开或者创建文件的时候默认的路径是相对路径,也就是在当前目录下打开。报错原因是给出路径不正确,在我这种情况下应该给出绝对路径,绝对路径要以/开头。
将代码改成:
with open("/" + os.path.join(pwd_p, "train_mask.txt"), 'w') as f:
for file in masks:
f.write(file)
Then bug fixed.
还有比较重要的一点就是要将open的第二个参数mode置为w!!!
推荐阅读
-
Django报错:python: can‘t open file ‘manage.py‘: [Errno 2] No such file or directory
-
python: can‘t open file ‘sqlmap.py‘: [Errno 2] No such file or directory
-
Python open: FileNotFoundError: [Errno 2] No such file or directory
-
IOError: [Errno 2] No such file or directory
-
Yum:[Errno 5] [Errno 2] No such file or directory
-
Yum:[Errno 5] [Errno 2] No such file or directory
-
FileNotFoundError: [Errno 2] No such file or directory:
-
Yum:[Errno 5] [Errno 2] No such file or directory
-
libiconv.so.2 cannot open shared object file: No such file or directory
-
libmatio.so.2: cannot open shared object file: No such file or directory