0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

pythonメモ

Last updated at Posted at 2020-11-28
#!/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)
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?