SIMOrthoProgram-Orth_LT1AB-.../Ortho/tool/file/fileHandle.py

88 lines
2.9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

# -*- coding: UTF-8 -*-
"""
@Project : microproduct
@File : fileHandle.py
@Function : 文件创建、删除、解压、打包
@Contact :
@Author:SHJ
@Date:2022/11/6
@Version:1.0.0
"""
import os
import tarfile
import shutil
class fileHandle:
def __init__(self, debug_mode=False):
self.__debug_mode = debug_mode
def creat_dirs(self, path_list):
"""
创建文件夹
"""
for path in path_list:
if os.path.exists(path):
if self.__debug_mode is True:
continue
self.del_folder(path)
os.makedirs(path)
else:
os.makedirs(path)
def del_folder(self, dic):
"""
删除整个文件夹
"""
if self.__debug_mode is True:
return
if os.path.isdir(dic):
shutil.rmtree(dic)
def del_file(self, path_data):
"""
只删除文件,不删除文件夹
"""
for i in os.listdir(path_data): # os.listdir(path_data)#返回一个列表,里面是当前目录下面的所有东西的相对路径
file_data = path_data + '\\' + i # 当前文件夹的下面的所有东西的绝对路径
if os.path.isfile(file_data) is True: # os.path.isfile判断是否为文件,如果是文件,就删除.如果是文件夹.递归给del_file.
os.remove(file_data)
else:
self.del_file(file_data)
@staticmethod
def make_targz(output_filename, source_dir):
"""
一次性打包整个根目录。空子目录会被打包。
如果只打包不压缩,将"w:gz"参数改为"w:""w"即可。
:param output_filename:输出压缩包的完整路径eg:'E:\test.tar.gz'
:param source_dir:需要打包的跟目录eg: 'E:\testFfile\'打包文件夹里面的所有文件,'E:\testFfile'打包文件夹
"""
dir = os.path.split(output_filename)[0]
if os.path.exists(dir) is False:
os.makedirs(dir)
with tarfile.open(output_filename, "w:gz") as tar:
tar.add(source_dir, arcname=os.path.basename(source_dir))
@staticmethod
def de_targz(tar_gz_path, file_dir):
name = os.path.split(tar_gz_path)[1].rstrip('.tar.gz')
if os.path.exists(file_dir) is False:
os.makedirs(file_dir)
# 解压
t = tarfile.open(tar_gz_path)
t.extractall(path=file_dir)
@staticmethod
def copyfile2dir(srcfile, dir): # 复制函数
if not os.path.isfile(srcfile):
print("%s not exist!" % (srcfile))
else:
fpath, fname = os.path.split(srcfile) # 分离文件名和路径
if not os.path.exists(dir):
os.makedirs(dir) # 创建路径
shutil.copy(srcfile, dir + fname) # 复制文件
# if __name__ == '__main__':
# file = fileHandle()
# file.del_floder("I:\preprocessed")
# pass