# -*- coding: utf-8 -*-
import os
def printFile(rootDir):
allFiles = os.listdir(rootDir) #列出文件夹下所有文件和目录
for i in range(0, len(allFiles)):
# print(rootDir + allFiles[i])
path = os.path.join(rootDir, allFiles[i])
if not os.path.isfile(path):
print(path, " is a directory.")
else:
print(path, " is a file.")
# 得到一个文件夹下面的所有文件,不递归
def getAllFileOfADir(rootDir):
fileList = []
allFiles = os.listdir(rootDir) #列出文件夹下所有文件和目录
for i in range(0, len(allFiles)):
# print(rootDir + allFiles[i])
path = os.path.join(rootDir, allFiles[i])
if not os.path.isfile(path):
#print(path, " is a directory.")
pass
else:
#print(path, " is a file.")
fileList.append(path)
return fileList
def printList(l):
length = len(l)
for i in range(0, length):
print(l[i])
# recursionDepth为递归的深度,为1时,仅仅查找rootDir目录下的所有指定文件,
# 不再查找子目录
# Suffix为要查找的指定的文件后缀名列表
allFile = [] # global
def getAllFileOfADir(rootDir, recursionDepth, Suffix=None):
if(recursionDepth < 0):
return
#fileList = []
allFiles = os.listdir(rootDir) #列出文件夹下所有文件和目录
for i in range(0, len(allFiles)):
path = os.path.join(rootDir, allFiles[i])
if not os.path.isfile(path):
if(not(allFiles[i] == '.' or allFiles[i] == '..')):
getAllFileOfADir(path + '/', recursionDepth - 1, Suffix)
else:
if(Suffix != None):
for suffix in Suffix:
if(allFiles[i].find(suffix) > -1):
allFile.append(path)
break
else:
allFile.append(path)
# python 文件操作,非常方便
def dirOperate():
dir1 = "C:/"
dir2 = "g:/backUp/"
dir3 = "g:/lin"
file1 = "g:/people.lxe"
file2 = "G:/交通状态/00020时间.xlsx"
file3 = "G:/opencv3.4.0.zip"
dirList = []
dirList.append(dir1)
dirList.append(dir2)
dirList.append(dir3)
fileList = [file1, file2, file3]
for dir in dirList:
if os.path.exists(dir):
print(dir, " exists.")
else:
print(dir, " doesn't exists.")
for file in fileList:
if(os.path.exists(file)):
print(file, " exist!")
else:
print(file, " doesn't exists.")
print()
list_total = [dirList, fileList]
for fileSet in list_total:
for file in fileSet:
if os.path.exists(file):
print(file, " exists.")
if os.path.isfile(file):
print(file, " is a file.")
else:
print(file, " is a dictory")
if os.access(file, os.R_OK):
print(file, " is accessible to read.")
if os.access(file, os.W_OK):
print(file, "is accessible to write.")
if os.access(file, os.X_OK):
print(file, "is accessible to execute.")
else:
print(file, " doesn't exists.")
# os.rename(), os.remove(), os.move(), os.copy(), os.copytree()
def main():
rootDir1 = "F:/"
#printFile(rootDir1)
#file = getAllFileOfADir(rootDir1)
#printList(file)
#print("Total file: ", len(file))
rootDir2 = "F:/2345Downloads/"
# getAllFileOfADir(rootDir2, 0)
# getAllFileOfADir(rootDir2, 1, ['.exe', '.zip'])
# getAllFileOfADir(rootDir2, 2)
# printList(allFile)
# print("Total file: ", len(allFile))
dirOperate()
if __name__ == '__main__':
main()