파이썬에서 깔끔하게 임시 파일 관리하기

2025. 8. 10. 15:04연구하기, 지식

 파이썬으로 코딩 하다보면 임시 파일을 만들고 삭제해야할 때가 많다. 특히 음성 AI에 종사해 있는 나는 원음의 특정 구간을 청킹해 저장 후 다른 곳에서 사용하곤 한다. Numpy Array 형태로 직접 활용하면 좋지만 대부분의 라이브러리에서는 오디오의 경로를 직접 받게 되어 있어 곤란할 때가 많다. 이럴 때 굳이 temp 경로를 지정하고 직접 삭제를 해야할까?

 

그동안..

 우선 그동안 내가 했던 방식을 확인해보겠다. 임시 파일 경로를 미리 지정해주고, pydub 라이브러리를 사용해 0.1초 단위로 청킹해 저장 후 시간을 비교해보겠다. 코랩에서 진행해보겠다.

from pydub import AudioSegment
import os
import time
from tqdm import tqdm

audio_path = '/content/테스트오디오50분.wav'
temp_path = '/content/temp'

audio = AudioSegment.from_file(audio_path)
audio_length = len(audio)
chunk_size = 100 #ms
total_count = 0

start_time = time.time()
for i in tqdm(range(chunk_size, audio_length, 100)):
  chunk = audio[i-chunk_size:i]
  chunk.export(f'{temp_path}/temp.wav', format='wav')

  os.remove(f'{temp_path}/temp.wav')
  total_count += 1

end_time = time.time()
print(f'Time taken: {end_time - start_time}')
print(f'Total count: {total_count}')

  50분 짜리 오디오를 실행한 결과, 총 카운트 30,097번 , 총 시간은 약 3초이다. 

 

tempfile

https://docs.python.org/ko/3/library/tempfile.html

 

tempfile — Generate temporary files and directories

Source code: Lib/tempfile.py This module creates temporary files and directories. It works on all supported platforms. TemporaryFile, NamedTemporaryFile, TemporaryDirectory, and SpooledTemporaryFil...

docs.python.org

 파이썬에서는 나의 이런 고충을 예견이라도 했듯, 표준 라이브러리로 임시 파일 관리 기능을 넣어놨다. tempfile 라이브러리는 임시 파일들의 관리를 쉽게 해준다. 임시 파일의 위치를 따로 지정해주지 않고 삭제할 필요도 없다. 코드는 다음과 같다.

from pydub import AudioSegment
import time
from tqdm import tqdm
import tempfile

audio_path = '/content/테스트오디오50분.wav'

audio = AudioSegment.from_file(audio_path)
audio_length = len(audio)
chunk_size = 100  # ms
total_count = 0

start_time = time.time()
for i in tqdm(range(chunk_size, audio_length, chunk_size)):
    chunk = audio[i-chunk_size:i]

    with tempfile.NamedTemporaryFile(suffix=".wav", delete=True) as tmp:
        chunk.export(tmp.name, format='wav')
        tmp.seek(0)

    total_count += 1

end_time = time.time()
print(f'Time taken: {end_time - start_time:.2f} seconds')
print(f'Total count: {total_count}')

 위와 똑같은 로직이지만 별도의 경로 지정이나 삭제를 하지 않았다. delete 파라미터를 True로 바꾸면 with 문이 끝나면 자동으로 삭제 된다. 또한 dir 파라미터로 경로도 지정해줄 수 있다. 코드가 깔끔해지고 있어보이기는 한다. 다만, 실행 속도는 느려졌다... 11초가 나왔다. 그리고 지금 보니 그닥 코드의 경제성도 보이지 않는다. '그냥 하던대로 하자' 라는 결론을 내고 싶었으나 다른 방법을 찾았다.

 

BytesIO

https://docs.python.org/ko/3.13/library/io.html

 

io — Core tools for working with streams

Source code: Lib/io.py Overview: The io module provides Python’s main facilities for dealing with various types of I/O. There are three main types of I/O: text I/O, binary I/O and raw I/O. These ar...

docs.python.org

 파일 IO를 굳이 거치지 않더라고 메모리만 활용할 수 있는 방법이다.  io라는 라이브러리에 BytesIO 를 사용하면 굳이 IO를 하지 않고도 사용할 수 있다. 실시간 소켓으로 음성 패킷을 받아 패킷을 처리하고 리턴을 해줄때 유용하게 사용할 수 있다. 

from pydub import AudioSegment
import time
from tqdm import tqdm
from io import BytesIO

audio_path = '/content/테스트오디오50분.wav'

audio = AudioSegment.from_file(audio_path)
audio_length = len(audio)
chunk_size = 100  # ms
total_count = 0

start_time = time.time()
for i in tqdm(range(chunk_size, audio_length, chunk_size)):
    chunk = audio[i-chunk_size:i]

    buf = BytesIO()
    chunk.export(buf, format='wav')
    buf.seek(0)

    total_count += 1

end_time = time.time()
print(f'Time taken: {end_time - start_time:.2f} seconds')
print(f'Total count: {total_count}')

 코드는 위와 같고 시간은 0.5초 밖에 되지 않는다. 파일 경로를 받는 라이브러리나 모델에서 buf를 파일 경로에 넣으면 바로 사용가능하다. 하지만 BytesIO를 파일 경로 처럼 받는 곳에서만 사용 가능하다. 많은 곳에서 아마 지원을 할거다. pydub만해도 buf 를 넣어서 오디오로 불러오는 것이 가능했다.

 

결론

 오늘도 실행 시간을 줄이는 방법을 찾아서 기쁘다. 대 AI 시대에서 1분 1초는 서비스 품질을 결정하는 중요한 요소이다. 이걸 더많이 테스트해서 많은 곳에 적용할 수 있을 것 같다. 파이썬은 참 배우기 쉽고 만들고자 하는 것을 구현하기가 용이하다. 하지만 한 스텝 한 스텝 발전하기엔 엄청 어려운 언어 같다. 공부할 것이 생겼다. 

728x90

'연구하기, 지식' 카테고리의 다른 글

uv 사용해보기  (5) 2025.08.29
NeMo Multi-Scale Diarization Decoder  (9) 2025.08.12
Supabase DB 사용해보기  (3) 2025.07.06
Gemma3 - 무료 멀티모달 LLM 모델 사용하기  (3) 2025.06.29
JIT 컴파일과 데코레이터  (2) 2025.06.09