# encoding=utf-8
import os
class FileTools(object):
@staticmethod
def get_abs_path(path):
"""
获取文件绝对路径
:param path: 输入的是相对路径/类似于 ~ 这种路径
:return: 返回绝对路径,但是路径真实性,不一定
"""
return os.path.abspath(os.path.expanduser(path))
def make_path(self, path, file_=False):
"""
根据输入的路径创建文件夹或者文件
:param path: 输入的路径(支持相对路径)
:param file_: True:想要创建文件, False:创建文件夹
:return:
"""
abs_path = self.get_abs_path(path)
if not file_ and not os.path.exists(abs_path):
os.makedirs(abs_path)
return True
elif file_ and os.path.exists(abs_path) and os.path.isdir(abs_path):
raise Exception("[{}] is a dir and it already exists".format(abs_path))
elif file_ and not os.path.exists(abs_path):
with open(abs_path, "w"):
return True
else:
return True
def get_dir_files(self, dir_path, get_all=False):
"""
遍历文件夹下的所有文件
:param dir_path:
:return:
"""
abs_path = self.get_abs_path(dir_path)
all_dir_list = []
all_file_list = []
root_1 = ""
for root, dirs, files in os.walk(abs_path):
# root 表示当前正在访问的文件夹路径
# dirs 表示该文件夹下的子目录名list
# files 表示该文件夹下的文件list
if not get_all and root == abs_path:
return root, [os.path.join(root, dir) for dir in dirs], [os.path.join(root, file) for file in files]
root_1 = root if not root_1 else root_1
all_dir_list.extend([os.path.join(root, dir) for dir in dirs])
all_file_list.extend([os.path.join(root, file) for file in files])
return root_1, all_dir_list, all_file_list
if __name__ == '__main__':
file_tools = FileTools()
Python 面试100讲(基于Python3.x)