目录操作 python

  1. 输出当前路径
import os
print(os.getcwd())
  1. 输出文件的绝对路径
import os
print(os.path.abspath('message.txt'))
  1. 判断路径是否存在,不存在则创建,存在就提示存在
import os
path = '\dddd\ddd'
if not os.path.exists(path):
	os.mkdir(path)
	print('create')
else:
	print('existed')
  1. 创建多级目录
path = "C:\\Users\\julie.wang\\PycharmProjects\\untitled\\TBD"
os.makedirs(path)
os.rmdir(path)  #删除空目录

import shutil
shutil.rmtree(path) #删除非空目录
  1. 遍历目录
path = "C:\\Users\\julie.wang\\PycharmProjects\\untitled\\TBD"
os.makedirs(path)
tuples = os.walk(path)
for tuple in tuples:
    print(tuple)
os.rmdir(path)
  1. 遍历目录
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))
  1. 删除文件
import os
path = "message.txt"
if os.path.exists(path):
    os.remove(path)
    print("deleted")
else:
    print("none")
  1. 重命名文件
import os

path = "message2.txt"
path2 = "message.txt"
if os.path.exists(path):
    os.rename(path, path2)
else:
    print("not existed")

你可能感兴趣的:(Python)