Contents
9.9. 获取当前的路径¶
#!/usr/bin/env python
#-*- coding:utf8 -*-
import os
#获取当前的目录
print("当前目录是:{}".format(os.getcwd()))
#获取目录中的内容
print("目录中的内容有:{}".format(os.listdir()))
#创建目录
if not os.path.exists("test_hu"):
print("开始创建目录.....test_hu")
os.mkdir("test_hu")
else:
print("目录中的内容有:{}".format(os.listdir()))
#删除目录
print("开始删除目录......test_hu",)
os.rmdir("test_hu")
print("目录中的内容有:{}".format(os.listdir()))
os.mkdir("test_hu")
#判断是否是目录
print("判断是否是目录?")
print(os.path.isdir("test_hu"))
print(os.path.isdir("fab.txt"))
#判断是否是文件
print("判断是否为文件?")
with open("fab1.txt","w+") as f:
f.write("hello this is file test")
print(os.path.isfile("fab1.txt"))
print(os.path.isfile("test_hu"))
split(p):
"""Split a pathname.
Return tuple (head, tail) where tail is everything after the final slash.
Either part may be empty."""
dirname(p):
"""Returns the directory component of a pathname"""
return split(p)[0]
basename(p):
"""Returns the final component of a pathname"""
return split(p)[1]
# 返回一个除去文件扩展名和扩展名的二元组
splitext(p)
#!/usr/bin/env python
# -*- coding:utf8 -*-
# auther; 18793
# Date:2019/8/18 12:42
# filename: 拆分路径.py
import os
path = "/home/lmx/t/access.log"
# 返回一个元祖,包含路径和文件名
print(os.path.split(path))
# 返回文件的路径
print(os.path.dirname(path))
# 返回文件的名称
print(os.path.basename(path))
# 返回一个除去文件扩展名和扩展名的二元组
print(os.path.splitext(path))
# 获取文件路径
print(os.getcwd())
print(os.path.abspath('.'))
# 返回本路径的上一层路径
print(os.path.abspath('..'))
# 拼接上层路径 + /hu/a.py
print(os.path.abspath('../hu/a.py'))
# 拼接上层路径 + /hu/hu.py
print(os.path.join(os.path.abspath('.'), 'hu', 'hu.py'))