2021년 10월 3일 일요일

python remove oldest file (오래된 파일 지우기)


오래된 파일을 삭제하는 예제입니다.

한번 호출하면 하나만 삭제합니다. 특정폴더의 갯수를 유지하는데 사용할 수 있습니다. 

실행을 해보면 처음에는 100.txt 200.txt 300.txt 파일 3개 만들어 두고 오래된 파일을 하나 삭제합니다. 오래된 파일은 100.txt가 되겠습니다.

sorted함수에서 정렬할때 사용하는 함수로 key에 목록값을 넣어서 정렬하게 됩니다. os.path.getctime()여기 인자에 파일이 들어와서 시간이 획득한것을 키로 정렬을 하게 되고, [0]은 첫번째 항목이므로 오래된 파일 정보를 가져오게 됩니다.

import shutil
import os

def write_file(filename,str_data):
	with open(filename, 'w') as fp:
		fp.write(str_data)
		fp.close()

def remove_oldest_file(folder,rcount=-1):
	if len(os.listdir(folder))==0:
		return None
	ret = []
	if rcount==-1:
		oldest_file = (sorted([folder+"/"+f for f in os.listdir(folder)], key=os.path.getctime))[0]
		os.remove(oldest_file)
		ret.append(oldest_file)
	else:
		while len(os.listdir(folder))>rcount:
			oldest_file = (sorted([folder+"/"+f for f in os.listdir(folder)], key=os.path.getctime))[0]
			os.remove(oldest_file)
			ret.append(oldest_file)
			
	return ret

if __name__ == "__main__":
	shutil.rmtree("temp",ignore_errors=True)
	os.makedirs("temp")

	write_file("temp/100.txt","*300")
	write_file("temp/200.txt","*200")
	write_file("temp/300.txt","*100")
	
	print("temp list:",os.listdir("temp"))
	print("removed:",remove_oldest_file("temp"))
	print("temp list:",os.listdir("temp"))
	
	write_file("temp/400.txt","*400")
	write_file("temp/500.txt","*500")
	
	print("temp list:",os.listdir("temp"))
	print("removed:",remove_oldest_file("temp",2))
	print("temp list:",os.listdir("temp"))
	
	shutil.rmtree("temp",ignore_errors=True)

인자 rcount는 해당폴더에 파일을 몇개 유지할지 설정하는 인자입니다. 2로 입력하면 해당폴더에 파일은 2개남 남고 예전 파일들은 모두 지우게 됩니다.

결과
C:\Users\USER\Documents\sourcecode\python\example>python 16_remove_oldest_file.py
temp list: ['100.txt', '200.txt', '300.txt']
removed: ['temp/100.txt']
temp list: ['200.txt', '300.txt']
temp list: ['200.txt', '300.txt', '400.txt', '500.txt']
removed: ['temp/200.txt', 'temp/300.txt']
temp list: ['400.txt', '500.txt']

댓글 없음:

댓글 쓰기