小编给大家分享一下解决python目录名无效错误的方法,希望大家阅读完这篇文章后大所收获,下面让我们一起去探讨吧!

python目录名无效错误的解决方法是:1、利用os.getcwd()获取当前文件路径path;2、检查传入的path是否为当前目录位置;3、若不是,将获取的path替换即可。

解决方案:

这个目录名无效困扰我很久,明明目录路径没问题啊,文件也有,为什么报错呢?

原来这个问题是因为只需要path信息,不要写到文件。

print(“获取当前文件路径——”+os.path.realpath(file))#获取当前文件路径parent=os.path.dirname(os.path.realpath(file))print(“获取其父目录——”+parent)#从当前文件路径中获取目录garder=os.path.dirname(parent)print(“获取父目录的父目录——”+garder)print(“获取文件名”+os.path.basename(os.path.realpath(file)))#获取文件名

当前文件的路径

pwd=os.getcwd()print(“当前运行文件路径”+pwd)

当前文件的父路径

father_path=os.path.abspath(os.path.dirname(pwd)+os.path.sep+“.”)print(“运行文件父路径”+father_path)

当前文件的前两级目录

grader_father=os.path.abspath(os.path.dirname(pwd)+os.path.sep+“…”)print(“运行文件父路径的父路径”+grader_father)

看完了这篇文章,相信你对解决python目录名无效错误的方法有了一定的了解,想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!