路径-os.Path模块
-
路径是否存在
os.path.exists(path) -
路径是否文件
os.path.isfile(path) -
路径是否目录
os.path.isdir(path) -
绝对路径
os.path.abspath(path) -
文件路径
os.path.dirname(path) -
文件名
os.path.basename(path)
import os
if os.path.exists("1.txt"):
print("True")
else:
print("False")
文件
-
创建
-
写入文件
def createFile(filePath, fileFullName, content): full_path = '%s/%s' % (filePath, fileFullName) file = open(full_path, 'w',encoding="utf-8") file.write(content)
-
-
删除
import os
os.remove("1.txt")
文件夹/目录
-
创建
父目录不存在的时候:os.makedirs(path)会创建父目录
os.mkdir(path)不会创建
-
删除
os.rmdir(“dir”) 只能删除空目录
shutil.rmtree(“dir”) 空目录、有内容的目录都可以删
综合应用
删除指定目录
无敌简洁优美,绝了
import shutil
def delFold(foldPath,delFoldState):
"""
删除该文件夹里的所有文件
delFoldState: 0:删除子文件,保留所有文件夹 1:删除子文件和子文件夹 2:删除子文件、子文件夹和自身目录
"""
for foldabsPath, childFolds, childFiles in os.walk(foldPath):
for fileName in childFiles:
print(foldabsPath,fileName)
filePath=os.path.join(foldabsPath,fileName)
os.remove(filePath)
print(foldabsPath)
if not foldabsPath==foldPath and delFoldState>=1:
shutil.rmtree(foldabsPath)
if delFoldState==2:
shutil.rmtree(foldPath)
递归删除文件,排除指定文件夹名、文件名
def isFold(filePath):
return os.path.isdir(filePath)
def isFile(filePath):
return os.path.isfile(filePath)
def isEmptyFold(filePath):
return not os.listdir(filePath)
# 递归删除文件,排除指定文件夹、文件名
def deleteFiles(path, remainDirsList, remainfilesList):
# global backUpFoldPath
# backUpFoldPath = backUpFoldPath.replace('/', '\\')
dirsList = []
dirsList = os.listdir(path)
for f in dirsList:
filePath = os.path.join(path, f)
filePath = filePath.replace('/', '\\')
if isFold(filePath):
# print "it's a directory"
if f not in remainDirsList:
if isEmptyFold(filePath):
print("empty dir:%s " % filePath)
else:
deleteFiles(filePath, remainDirsList, remainfilesList)
else:
print("keep this dir: %s" % filePath)
elif isFile(filePath):
# print "it's a normal file"
if f not in remainfilesList:
os.remove(filePath)
else:
print("keep this file: %s" % filePath)
else:
print ("it's a special file(socket,FIFO,device file):%s" % filePath)
# 获取父级路径
def getParentDir(path):
path = path.replace('/', '\\')
index = path.rfind("\\")
result = path[0:index]
return result
# print("%s : %s: %s" % (path, index, result))
# 递归删除文件夹
def deleteFold(path, remainDirsList):
global backUpFoldPath
path = path.replace('/', '\\')
backUpFoldPath = backUpFoldPath.replace('/', '\\')
# 删除不在保留清单的空文件夹
if isFold(path):
foldName = path.rsplit('\\', 1)[1]
if foldName not in remainDirsList:
if isEmptyFold(path):
shutil.rmtree(path)
print("delete empty dir:%s " % path)
fileParentPath = getParentDir(path)
if fileParentPath == backUpFoldPath:
return
deleteFold(fileParentPath, remainDirsList)
return
dirsList = []
dirsList = os.listdir(path)
for f in dirsList:
filePath = os.path.join(path, f)
if isFold(filePath):
# print "it's a directory"
if f not in remainDirsList:
if isEmptyFold(filePath):
shutil.rmtree(filePath)
print("delete empty dir:%s " % filePath)
fileParentPath = getParentDir(filePath)
# 删除不在保留清单的空文件夹后,遍历其父级路径
deleteFold(fileParentPath, remainDirsList)
else:
deleteFold(filePath, remainDirsList)
else:
print("keep this dir: %s" % filePath)
获取当前文件夹下所有文件名,指定排除特定后缀的文件
import os
def isFold(filePath):
return os.path.isdir(filePath)
# 获取指定目录,排除指定后缀的所有文件,存储到filesList
def listFold(path, excludeSuffix, filesList):
for file in os.listdir(path):
file_path = os.path.join(path, file)
if isFold(file_path):
listFold(file_path, excludeSuffix, filesList)
else:
if not os.path.splitext(file)[1] == excludeSuffix:
filesList.append(file_path)
def main():
filesList=[]
listFold("D:/Test", ".exe", filesList)
拷贝文件,自动生成文件夹,拷贝时支持指定文件不拷贝
# 拷贝文件,自动生成文件夹,拷贝时支持指定文件不拷贝
def copyFile(sourceFilePath, destinationFilePath, noCopyList):
# 去除尾部 \ 符号
fileFullName = destinationFilePath.split("\\")[-1]
foldPath = destinationFilePath[0:destinationFilePath.find(fileFullName)]
isExists = os.path.exists(foldPath)
if not isExists:
os.makedirs(foldPath)
if not fileFullName in noCopyList:
shutil.copy2(sourceFilePath, destinationFilePath)
else:
print("[nocopy]: %s" % destinationFilePath)