pyhon搜尋目錄下的檔案或資料夾
pyhon搜尋目錄下的檔案或資料夾
# !/usr/bin/env python
# -*-coding:utf-8-*-
"""
Copyright(c)2018,浙江大華
file: sambaCenter.py
author: 27711
date: 2018/11/24
version: 1.0
describe:
"""
import os
import subprocess
class CFileInfo(object):
def __int__(self):
self.fileType = 0 # 0:dir 1:file
self.fileName = ""
self.fileSize = 0 # Byte# ,if dir 0
self.parentDir = "" # "/home/10001"
class CSambaCenter(object):
def __init__(self):
pass
def scanFiles(self, userId, dir="/home", preFix=None, postFix=None):
"""
搜尋指定目錄下的匹配字首或字尾的檔案和資料夾
:param userId: 使用者ID 如10001
:param dir:指定目錄,若為檔案則返回檔案詳情
:param preFix:字首如:“test_”
:param postFix:後續如:".py"
:return:目錄和檔案的list詳情
"""
try:
if preFix is None and postFix is None:
return self.getAllDirs(userId, dir)
listFilesInfo = []
for dirpath, dirs, files in os.walk(dir):
for dirname in dirs:
if dirname[0] == '.': # 剔除隱藏
pass
if postFix:
if dirname.endswith(postFix):
fileInfo = CFileInfo()
fileInfo.fileName = dirname
fileInfo.parentDir = dirpath
listFilesInfo.append(fileInfo)
elif preFix:
if dirname.startswith(preFix):
fileInfo = CFileInfo()
fileInfo.fileName = dirname
fileInfo.parentDir = dirpath
listFilesInfo.append(fileInfo)
for file in files:
if file[0] == '.': # 剔除隱藏
pass
if postFix:
if file.endswith(postFix):
fileInfo = CFileInfo()
fileInfo.fileType = 1
fileInfo.fileSize = os.path.getsize(file)
fileInfo.fileName = file
fileInfo.parentDir = dirpath
listFilesInfo.append(fileInfo)
elif preFix:
if file.startswith(preFix):
fileInfo = CFileInfo()
fileInfo.fileType = 1
fileInfo.fileSize = os.path.getsize(file)
fileInfo.fileName = file
fileInfo.parentDir = dirpath
listFilesInfo.append(fileInfo)
return listFilesInfo
except Exception as e:
print(e)
return None
if __name__ == '__main__':
pass
剔除隱藏的檔案和資料夾,for dirpath, dirs, files in os.walk(dir),通過python庫介面方便,方案效能上需要再優化,若檔案較多,不建議次方案