写在前面:本博客的目的是记录日常工作中使用到的常见Python脚本,为技术栈为非Python的同学提供可直接借鉴的代码,非专业Python教程,只保证可用,不保证最优。
说明:当前路径下存在若干log文件夹,其格式为202309281621_LOG,其中包含大量.gz文件,需要把.gz文件解压并存放至同一个TXT中,便于查阅
import os # os操作的库,这里主要用到os.path
import gzip # 解压文件的库
current_directory = os.path.dirname(os.path.abspath(__file__))
print(current_directory)
for file_name in os.listdir(current_directory):
str_file_name = str(current_directory)
if str_file_name[-3:]=='LOG':
path = current_directory + "\\" + str_file_name
# 解压gz文件
for file_name_2 in os.listdir(path):
str_file_name_2 = str(file_name_2)
if str_file_name_2[-3:]==".gz":
g = gzip.GzipFile(mode="rb", fileobj=open(path + "\\" + str_file_name_2, 'rb'))
open(path + "\\" + str_file_name_2.replace(".gz",""), "wb").write(g.read)
open(current_directory + "\\log" + str_file_name + ".txt", "w")
# 整合解压后的文件
for file_name_2 in os.listdir(path):
str_file_name_2 = str(file_name_2)
if str_file_name_2[-3:]!=".gz":
f = open(path + "\\" + str_file_name_2, "rb").read()
log = open(current_directory + "\\log" + str_file_name + ".txt", 'ab')
log.write(f)
os.system("pause")
我们