#!/usr/bin/env python3
# YYYYMMDD Get
import datetime
today = datetime.date.today()
yyyymmdd = today.strftime('%Y%m%d')
yyyymmddhhmmss = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
# ファイルの定義
dir = '/opt/script/log'
file = '/opt/script/log/hoge.txt'
filecopy = file + '-' + yyyymmddhhmmss
filegz = filecopy + '.gz'
#--- Function ----------------------------------#
# File Copy
def func_file_copy(file, filecopy):
print('func_file_copy')
import shutil
shutil.copyfile(file, filecopy)
# File Gzip
def func_gzip(file, filegz):
print('func_gzip')
import gzip
import shutil
with open(file, 'rb') as f_in:
with gzip.open(filegz, 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
# File Delete
def func_delete_file(file):
print('func_delete_file')
import os
os.remove(file)
# File List
def function_file_list():
print('function_file_list')
import os
from operator import itemgetter
global filelists
filelists = []
for l_file in os.listdir(path=dir):
base, ext = os.path.splitext(l_file)
if ext == '.gz':
l_file_full = dir + '/' + l_file
filelists.append([l_file_full, os.path.getctime(l_file_full)])
filelists.sort(key=itemgetter(1), reverse=True)
for name in filelists:
print(name)
def function_file_list_delete():
MAX_CNT = 3
for i,file in enumerate(filelists):
if i > MAX_CNT - 1:
print('{}は削除します'.format(file[0]))
filedelete = format(file[0])
func_delete_file(filedelete)
def function_file_truncate(file):
open(file, 'w').close()
#--- Main --------------------------------------#
func_file_copy(file, filecopy)
func_gzip(filecopy, filegz)
func_delete_file(filecopy)
print('--- Before ------------------------------')
function_file_list()
print('-----------------------------------------')
function_file_list_delete()
print('--- After -------------------------------')
function_file_list()
print('-----------------------------------------')
function_file_truncate(file)
More than 3 years have passed since last update.
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme