Python操作文件封裝
- 解壓文件
- 刪除文件
- 寫入文件
- 遞歸文件
- 解決亂碼
- 刪除目錄
- 創(chuàng)建目錄
- 去重?cái)?shù)據(jù)
# -*- coding:utf-8 -*-
import os
import re
import time
import operator
import zipfile
import rarfile
import shutil
# 找交集脚草,差集
def find_diff_str(list1,list2):
A = set(list1).intersection(set(list2)) #交集
B = set(list1).union(set(list2)) # 并集
C = set(list1).difference(set(list2)) #差集,在list1中但不在list2中的元素
D = set(list2).difference(set(list1)) #差集,在list2中但不在list1中的元素
return A,B,C,D
# 對(duì)個(gè)獲取指定目錄的所有文件
def get_all_files(dir):
fileList = []
"""遍歷獲取指定文件夾下面所有文件"""
if os.path.isdir(dir):
filelist = os.listdir(dir)
for ret in filelist:
filename = dir + "\\" + ret
if os.path.isfile(filename):
fileList.append(filename)
return fileList
# 對(duì)個(gè)獲取指定目錄的所有文件
def get_file_list_by_walk(dir):
fileList = []
"""使用listdir循環(huán)遍歷"""
if not os.path.isdir(dir):
return fileList
dirlist = os.walk(dir)
for root, dirs, files in dirlist:
for fi in files:
fileList.append(os.path.join(root, fi))
return fileList
#指定文件路徑獲取文件最后文件的路徑包含文件
#如:D:\test\file.txt 返回的結(jié)果為:D:\test\
def get_file_root(path):
#獲取文件名
#return os.path.split(path)[1]
# 獲取文件路徑
return os.path.split(path)[0]
#指定文件路徑獲取文件最后文件的路徑包含文件
#如:D:\test\file.txt 返回的結(jié)果為:file.txt
def get_file_name(path):
return os.path.basename(path)
# 編碼轉(zhuǎn)換
def decode(str):
try:
string = str.encode('cp437').decode('gbk')
except:
string = str.encode('utf-8').decode('utf-8')
return string
# 創(chuàng)建目錄
def mkdir(path):
# 去除尾部 \ 符號(hào)
pathx = path.strip().rstrip("\\")
# 判斷路徑是否存在
# 存在 True
# 不存在 False
isExists = os.path.exists(pathx)
# 判斷結(jié)果
if not isExists:
# 如果不存在則創(chuàng)建目錄創(chuàng)建目錄操作函數(shù)
os.makedirs(path)
print(path + ' 創(chuàng)建成功')
return True
else:
# 如果目錄存在則不創(chuàng)建,并提示目錄已存在
print(path + ' 目錄已存在')
return False
"""
參考文章 https://www.jb51.net/article/180325.htm
https://blog.csdn.net/WANGYONGZIXUE/article/details/111576380
在一個(gè)數(shù)組里面找重復(fù)值
python處理去重用set函數(shù)
"""
def find_repeat_val_by_list(list):
values = {}
for i in list:
if list.count(i)>1:
values[i] = list.count(i)
return values
"""
通過指定文件路徑文件進(jìn)行讀取內(nèi)容
如:D:\test\file.txt
"""
def reader_file(path):
#解決亂碼問題
fi = open(path,'r',encoding='utf-8',errors = 'ignore')
strs = []
#splitlines解決不換行\(zhòng)n輸出
for line in fi.read().splitlines():
if(len(line)>0):
strs.append(line)
return str
"""
創(chuàng)建一個(gè)txt文件,并向文件寫入msg
@file_dir參數(shù) 代表文件目錄 如:D:\test
@file_name參數(shù) 代表文件名稱 如:file.txt
@msg參數(shù) 代表要寫入文件的內(nèi)容信息
"""
def writer_to_file(file_dir, file_name, msg):
# 先創(chuàng)建目錄
mkdir(file_dir)
# 再打開文件
full_path = file_dir + "\\" + file_name
fi = open(full_path, 'w')
# 寫入文件
fi.write(msg)
fi.close()
#刪除文件
def del_files(dir_path):
# os.walk會(huì)得到dir_path下各個(gè)后代文件夾和其中的文件的三元組列表,順序自內(nèi)而外排列急膀,
for root, dirs, files in os.walk(dir_path, topdown=False):
# 第一步:刪除文件
for file_name in files:
try:
os.remove(os.path.join(root, file_name)) # 刪除文件
except Exception as e:
print(f'刪除文件,失敗原因?yàn)?{e}' )
pass
# 第二步:刪除空文件夾
for dir in dirs:
try:
os.rmdir(os.path.join(root, dir)) # 刪除一個(gè)空目錄
except Exception as e:
print(f'刪除空文件夾,失敗原因?yàn)?{e}' )
pass
# 創(chuàng)建目錄
def mkdir(path):
# 去除尾部 \ 符號(hào)
pathx = path.strip().rstrip("\\")
#print(f'pathx={pathx}')
# 判斷路徑是否存在
# 存在 True
# 不存在 False
isExists = os.path.exists(pathx)
# 判斷結(jié)果
if not isExists:
# 如果不存在則創(chuàng)建目錄創(chuàng)建目錄操作函數(shù)
os.makedirs(path)
print(path + ' 創(chuàng)建成功')
return True
else:
# 如果目錄存在則不創(chuàng)建,并提示目錄已存在
print(path + ' 目錄已存在')
return False
class File:
def __init__(self):
self.fileList = []
"""
遞歸列表文件
"""
def recursion_file(self, filepath):
files = os.listdir(filepath)
for file in files:
fi_d = os.path.join(filepath, file)
if os.path.isdir(fi_d):
self.recursion_file(fi_d)
else:
self.fileList.append(fi_d)
"""
獲取文件列表
"""
def get_file_list(self, filepath):
self.recursion_file(filepath)
return self.fileList
"""
解壓rar文件
需要安裝WinRar并且配置環(huán)境變量
pip install rarfile
返回失敗文件
"""
def un_rar(filepath):
fail_path = ''
try:
if os.path.isdir(filepath + "-file"):
pass
else:
zipname = filepath
extractpath = filepath.replace(".rar", "") + '-file'
rar = rarfile.RarFile(zipname)
rar.extractall(extractpath)
rar.close()
#os.remove(extractpath)
#print(f'成功文件:{get_file_name(filepath)}' )
except Exception as e:
print(f'失敗文件為:{get_file_name(filepath)}--->>un_rar Exception file fail' )
fail_path = filepath
pass
return fail_path
# 刪除空文件夾
def del_empty_file(dir_path):
for root, dirs, files in os.walk(dir_path, topdown=False):
for dir in dirs:
try:
os.rmdir(os.path.join(root, dir)) # 刪除一個(gè)空目錄
except Exception as e:
print(f'刪除空文件夾,失敗原因?yàn)?{e}' )
pass
"""
解壓zip文件 返回失敗文件
"""
def un_zip(filepath):
fail_path = ''
# 可以自己定義路徑
zipname = filepath
extractpath = filepath.replace(".zip", "") + '-file'
try:
# 注意壓縮格式選擇
frzip = zipfile.ZipFile(zipname, 'r', zipfile.ZIP_DEFLATED)
# 將所有文件加壓縮到指定目錄
frzip.extractall(extractpath)
frzip.close()
except Exception as e:
print(f'失敗文件為:{get_file_name(filepath)}' )
fail_path = filepath
pass
#解壓完成
all_path_file = []
all_path_dir = []
for root, dirs, files in os.walk(extractpath):
for file in files:
file_kv = {'name': file, 'path': root}
all_path_file.append(file_kv)
for dir1 in dirs:
# 文件深度
deep_count = len(root.split('\\'))
dir_kv = {'name': dir1, 'path': root, 'deep': deep_count}
all_path_dir.append(dir_kv)
# 一定是先文件再文件夾,否者重命名后文件夾內(nèi)的文件找不到,先是最大深度文件夾躏啰,所以需要深度排序
all_path_dir = sorted(all_path_dir, key=operator.itemgetter('deep'), reverse=True)
for dic in all_path_file + all_path_dir:
file_name = dic['name']
parent_path = dic['path']
file_name_ok = decode(file_name)
err_path_name = os.path.join(parent_path, file_name)
ok_path_name = os.path.join(parent_path, file_name_ok)
os.rename(err_path_name, ok_path_name) # 重命名文件
return fail_path
python讀取Excel推薦文章
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者