Python 파일 및 폴더 관리 자동화
Python은 강력한 파일 및 폴더 관리 기능을 제공하며, 이를 활용하면 반복적인 작업을 효율적으로 자동화할 수 있습니다. 이 글에서는 Python의 os
모듈과 shutil
모듈을 활용해 파일 및 폴더 관리 작업을 자동화하는 방법을 소개하겠습니다. 실제 예제를 통해 각 기능을 알아보고 실무에서 활용할 수 있는 방법도 제시합니다.
파일 및 폴더 관리를 위한 주요 모듈
Python에서 파일 및 폴더 관리를 위해 주로 사용되는 모듈은 다음과 같습니다:
- os 모듈: 운영 체제의 파일 시스템 작업을 수행합니다.
- shutil 모듈: 파일 및 폴더 복사, 이동 등 고수준의 작업을 지원합니다.
기본 파일 및 폴더 작업
1. 파일 및 폴더 존재 여부 확인
파일이나 폴더가 존재하는지 확인하려면 os.path.exists()
를 사용할 수 있습니다.
import os
# 파일 존재 여부 확인
file_path = "example.txt"
if os.path.exists(file_path):
print(f"파일이 존재합니다: {file_path}")
else:
print(f"파일이 존재하지 않습니다: {file_path}")
# 폴더 존재 여부 확인
folder_path = "example_folder"
if os.path.exists(folder_path):
print(f"폴더가 존재합니다: {folder_path}")
else:
print(f"폴더가 존재하지 않습니다: {folder_path}")
2. 파일 생성 및 삭제
파일을 생성하거나 삭제하는 작업은 open()
과 os.remove()
를 이용할 수 있습니다.
# 파일 생성
with open("new_file.txt", "w") as file:
file.write("자동화된 파일 생성 예제입니다.")
print("파일이 생성되었습니다: new_file.txt")
# 파일 삭제
if os.path.exists("new_file.txt"):
os.remove("new_file.txt")
print("파일이 삭제되었습니다: new_file.txt")
3. 폴더 생성 및 삭제
폴더를 생성하거나 삭제하려면 os.mkdir()
와 os.rmdir()
를 사용할 수 있습니다.
# 폴더 생성
if not os.path.exists("new_folder"):
os.mkdir("new_folder")
print("폴더가 생성되었습니다: new_folder")
# 폴더 삭제
if os.path.exists("new_folder"):
os.rmdir("new_folder")
print("폴더가 삭제되었습니다: new_folder")
주의:
os.rmdir()
는 폴더가 비어 있어야만 삭제할 수 있습니다. 폴더 내 파일을 삭제하려면shutil
모듈을 사용하세요.
고급 파일 및 폴더 작업
1. 파일 및 폴더 복사
shutil.copy()
와 shutil.copytree()
를 사용해 파일과 폴더를 복사할 수 있습니다.
import shutil
# 파일 복사
shutil.copy("example.txt", "backup_example.txt")
print("파일이 복사되었습니다: backup_example.txt")
# 폴더 복사
shutil.copytree("example_folder", "backup_folder")
print("폴더가 복사되었습니다: backup_folder")
2. 파일 및 폴더 이동
shutil.move()
를 사용하면 파일과 폴더를 이동할 수 있습니다.
# 파일 이동
shutil.move("example.txt", "moved_example.txt")
print("파일이 이동되었습니다: moved_example.txt")
# 폴더 이동
shutil.move("example_folder", "moved_folder")
print("폴더가 이동되었습니다: moved_folder")
3. 폴더 내 파일 목록 확인
os.listdir()
를 이용하면 특정 폴더 내 파일과 하위 폴더 목록을 가져올 수 있습니다.
# 폴더 내 파일 목록 확인
folder_path = "example_folder"
if os.path.exists(folder_path):
files = os.listdir(folder_path)
print(f"{folder_path} 내 파일 목록:")
for file in files:
print(file)
4. 폴더 및 파일 재귀 삭제
shutil.rmtree()
를 이용하면 폴더와 하위 내용을 모두 삭제할 수 있습니다.
# 폴더 및 하위 파일 삭제
if os.path.exists("backup_folder"):
shutil.rmtree("backup_folder")
print("폴더와 모든 하위 내용이 삭제되었습니다: backup_folder")
실제 활용 예제: 특정 확장자의 파일 정리하기
폴더 내 특정 확장자의 파일을 다른 폴더로 이동하는 스크립트를 작성해 보겠습니다.
import os
import shutil
# 정리할 폴더 경로
source_folder = "source_folder"
destination_folder = "organized_folder"
extension = ".txt"
# 목적지 폴더 생성
if not os.path.exists(destination_folder):
os.mkdir(destination_folder)
# 파일 정리
for file_name in os.listdir(source_folder):
if file_name.endswith(extension):
source_path = os.path.join(source_folder, file_name)
destination_path = os.path.join(destination_folder, file_name)
shutil.move(source_path, destination_path)
print(f"파일 이동됨: {source_path} -> {destination_path}")
위 스크립트는 source_folder
내의 .txt
파일을 모두 organized_folder
로 이동합니다.
결론
Python의 파일 및 폴더 관리 기능을 활용하면 반복적이고 지루한 작업을 자동화할 수 있습니다. 본문에서 다룬 예제를 통해 기초적인 작업부터 고급 작업까지 실습해 보세요. 이를 활용하면 시간과 노력을 절약하고 생산성을 높일 수 있습니다.
앞으로도 Python의 강력한 기능을 활용한 다양한 자동화 주제를 소개하겠습니다.
'Python 고급' 카테고리의 다른 글
Python 정기 작업 스케줄링 (0) | 2025.01.13 |
---|---|
Python 이메일 전송 (0) | 2025.01.12 |
Python 브라우저 자동화를 위한 Selenium 사용 (0) | 2025.01.10 |
Python 데이터베이스 쿼리 최적화 팁 (0) | 2025.01.09 |
Python MySQL과 PostgreSQL 연동 방법 (0) | 2025.01.08 |