😂遇到过的一个问题:使用相对路径进行文件的上下文操作时,抛出异常:FileNotFoundError
with open('../data/{}.json'.format(filename), 'r', encoding="utf-8") as f:
j = json.load(f)
解决办法:使用os.path模块方法 定位父目录的绝对位置
#需求:要读取的文件都放在父目录的子目录下
parent_path = os.path.dirname(__file__) #获取该模块的所在的目录路径
grand_path=os.path.dirname(current_path) #获取当前目录所在的父目录路径
- os模块常用方法:
- os.listdir(path): 列出path路径下的所有文件和目录
- os.getcwd(): 返回当前模块所在的工作目录
- ......
- os.path模块常用方法:
- os.path.isfile(path): 判断路径是否为文件
- os.path.isdir(path): 判断路径是否为目录
- os.path.join(path1,path2): 路径拼接,path1/path2
- os.path.exists(path): 判断路径是否存在
- os.path.basename(path): 返回文件名
- os.path.getmtime(path): 返回文件最近修改时间==>1595575619.7296095,可使用time模块将时间转换成local time: time.ctime(os.path.getmtime(path))==>eg: "Fri Jul 24 15:26:59 2020"
- os.path.getctime(path): 返回文件的创建时间
- ......