Python获取当前文件夹下的目录和文件
# !/usr/bin/env python
# -*-coding:utf-8-*-
"""
Copyright(c)2018
file: sambaCenter.py
author:
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 __list_dir(self, dir):
"""
获取指定用户指定目录下的当前层级的子目录和文件
:param dir: 指定目录'/home/10001',若为文件则返回文件详情
:return: 文件和文件夹的list详情,若失败,则返回None
"""
try:
if not os.path.exists(dir) or dir is None:
print("error path not exist ro param illegal")
return None fileInfoList = []
if os.path.isdir(dir):
dir_list = os.listdir(dir)
for cur_file in dir_list:
if cur_file[0] == '.': # 排除隐藏文件和文件夹
pass
path = os.path.join(dir, cur_file)
if os.path.isfile(path):
# print("{0}: is file".format(cur_file))
fileInfo = CFileInfo()
fileInfo.fileName = cur_file
fileInfo.fileSize = os.path.getsize(path)
fileInfo.parentDir = dir
fileInfo.fileType = 1
fileInfoList.append(fileInfo)
if os.path.isdir(path):
# print("{0}: is dir".format(cur_file))
fileInfo = CFileInfo()
fileInfo.fileName = cur_file
fileInfo.parentDir = dir
fileInfoList.append(fileInfo)
if os.path.isfile(dir):
fileInfo = CFileInfo()
fileInfo.fileName = os.path.splitext(dir)[0]
fileInfo.fileSize = os.path.getsize(dir)
fileInfo.parentDir = os.path.dirname(dir)
fileInfo.fileType = 1
fileInfoList.append(fileInfo) return fileInfoList
except Exception as e:
print(e)
return None
def getDirs(self, userId, dir="/home/27711"):
"""
获取指定用户指定目录下的当前层级的子目录和文件
:param userId:工号如10001
:param dir:指定目录,若为文件则返回文件详情
:return:目录和文件的list
"""
return self.__list_dir(dir) def getAllDirs(self, userId, dir="/home"):
"""
获取指定用户指定目录下的全部目录和文件
:param userId:用户ID
:param dir:指定目录,若为文件则返回文件详情
:return:目录和文件的list
"""
try:
if not os.path.exists(dir) or dir is None:
print("error path not exist ro param illegal")
return None listFilesInfo = []
for dirpath, dirs, files in os.walk(dir):
for dirname in dirs:
if dirname[0] == '.': # 剔除隐藏
pass
fileInfo = CFileInfo()
fileInfo.fileName = dirname
fileInfo.parentDir = dirpath
listFilesInfo.append(fileInfo)
for file in files:
if file[0] == '.': # 剔除隐藏
pass
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
文件数多的情况下,性能上,一次性获取全部的文件和文件夹不建议直接去文件系统读取,建议分级加载,提升用户体验,有应用层控制展示情形