Python之文件路径名的操作

使用 os.path 模块中的函数来操作路径名
import os

# 获取当前文件路径
path=os.path.abspath(__file__)  # 获取绝对路径 /home/zzy/PycharmProjects/MyTest/testPackage/secondPackage/文件与IO.py
print(path)
print(os.path.realpath(__file__))  # 获取真实路径  /home/zzy/PycharmProjects/MyTest/testPackage/secondPackage/文件与IO.py

# 文件基础名字
print(os.path.basename(path))  # 文件与IO.py

# 获取文件目录
print(os.path.dirname(path))   # /home/zzy/PycharmProjects/MyTest/testPackage/secondPackage

# 文件路径拼接
print(os.path.join("new","zzy",os.path.basename(path)))  # new/zzy/文件与IO.py

# 展开用户的主目录
print(os.path.expanduser("~/PycharmProjects/MyTest/testPackage/secondPackage"))   # /home/zzy/PycharmProjects/MyTest/testPackage/secondPackage

# 拆分文件扩展名
print(os.path.splitext(path))  # ('/home/zzy/PycharmProjects/MyTest/testPackage/secondPackage/文件与IO', '.py')

# 拆分文件名和目录
print(os.path.split(path))  # ('/home/zzy/PycharmProjects/MyTest/testPackage/secondPackage', '文件与IO.py')
对于任何的文件名的操作,你都应该使用 os.path 模块,特别是为了可移植性考虑的时候更应如此,
因为 os.path 模块知道Unix和Windows系统之间的差异并且能够可靠地处理类似

测试文件是否存在
print(os.path.exists("MyTest/testPackage"))  # False
print(os.path.exists("/home/zzy/PycharmProjects/MyTest/testPackage"))  # True
判断文件类型
print(os.path.isdir("/home/zzy/PycharmProjects/MyTest/testPackage/secondPackage"))  # True
print(os.path.isdir("/home/zzy/PycharmProjects/MyTest/testPackage/secondPackage/文件与IO.py"))  # False

print(os.path.isfile("/home/zzy/PycharmProjects/MyTest/testPackage/secondPackage/文件与IO.py"))  # True

print(os.path.islink("/home/zzy/PycharmProjects/MyTest/testPackage/secondPackage/文件与IO.py"))  # False
print(os.path.islink("/home/zzy/PycharmProjects/MyTest/testPackage/secondPackage"))  # False

 

 
 
posted on 2019-03-12 17:43  V神丫丫  阅读(391)  评论(0编辑  收藏  举报