- 输出当前路径
import os
print(os.getcwd())
- 输出文件的绝对路径
import os
print(os.path.abspath('message.txt'))
- 判断路径是否存在,不存在则创建,存在就提示存在
import os
path = '\dddd\ddd'
if not os.path.exists(path):
os.mkdir(path)
print('create')
else:
print('existed')
- 创建多级目录
path = "C:\\Users\\julie.wang\\PycharmProjects\\untitled\\TBD"
os.makedirs(path)
os.rmdir(path)
import shutil
shutil.rmtree(path)
- 遍历目录
path = "C:\\Users\\julie.wang\\PycharmProjects\\untitled\\TBD"
os.makedirs(path)
tuples = os.walk(path)
for tuple in tuples:
print(tuple)
os.rmdir(path)
- 遍历目录
path = "C:\\Users\\julie.wang\\PycharmProjects\\untitled\\TBD"
os.makedirs(path)
print("【",path,"】目录下的文件以及子目录")
for root,dirs,files in os.walk(path,topdown=True):
for name in dirs:
print("⚪",os.path.join(root,name))
for name in files:
print("×",os.path.join(root,name))
- 删除文件
import os
path = "message.txt"
if os.path.exists(path):
os.remove(path)
print("deleted")
else:
print("none")
- 重命名文件
import os
path = "message2.txt"
path2 = "message.txt"
if os.path.exists(path):
os.rename(path, path2)
else:
print("not existed")