今天使用python时遇到了这个问题
FileNotFoundError: [Errno 2] No such file or directory
在python写入文件时找不到文件,我一开始以为是权限的问题,但是在给相应的文件加上权限后仍然报错。
后来发现在运行python脚本时,计算的相对路径并不是从python文件所在位置计算的,而是从运行脚本的目录处开始计算。
解决方案:
修改python中的路径为绝对路径,或者在python文件所在文件夹处运行脚本。
import os cwd = os.getcwd() # Get the current working directory (cwd) files = os.listdir(cwd) # Get all the files in that directory print("Files in '%s': %s" % (cwd, files))
这会打印当前所在的目录及期中的所有文件,有助于帮助了解现在所处的位置。