νμΌ μλν
Pythonμ μ¬μ©νλ©΄ λ°λ³΅μ μΈ νμΌ μμ μ μλνν μ μμ΅λλ€. νμΌκ³Ό ν΄λλ₯Ό μμ±, μμ , μ΄λ, 볡μ¬νλ μμ μ μ½λλ‘ μ²λ¦¬ν΄λ³΄κ² μ΅λλ€.
ν΅μ¬ λͺ¨λβ
os λͺ¨λβ
μ΄μ체μ μ μνΈμμ©νλ κΈ°λ³Έ λͺ¨λμ λλ€.
import os
# νμ¬ μμ
λλ ν 리 νμΈ
current_dir = os.getcwd()
print(f"νμ¬ λλ ν 리: {current_dir}")
# λλ ν 리 λ³κ²½
os.chdir('/Users/username/Documents')
# λλ ν 리 λͺ©λ‘ 보기
files = os.listdir('.')
print(files)
# κ²½λ‘ κ²°ν© (μ΄μ체μ μ λ§κ² μλμΌλ‘)
path = os.path.join('folder', 'subfolder', 'file.txt')
print(path) # folder/subfolder/file.txt (macOS/Linux)
shutil λͺ¨λβ
κ³ μμ€ νμΌ μμ μ μν λͺ¨λμ λλ€.
import shutil
# νμΌ λ³΅μ¬
shutil.copy('source.txt', 'destination.txt')
# λ©νλ°μ΄ν° ν¬ν¨ 볡μ¬
shutil.copy2('source.txt', 'destination.txt')
# ν΄λ μ 체 볡μ¬
shutil.copytree('source_folder', 'destination_folder')
# νμΌ/ν΄λ μ΄λ
shutil.move('old_location.txt', 'new_location.txt')
# ν΄λ μμ (λ΄μ©λ¬Ό ν¬ν¨)
shutil.rmtree('folder_to_delete')
ν΄λ λ° νμΌ μμ±β
λλ ν 리 μμ±β
import os
# λ¨μΌ λλ ν 리 μμ±
if not os.path.exists('new_folder'):
os.mkdir('new_folder')
# μ€μ²© λλ ν 리 μμ±
os.makedirs('parent/child/grandchild', exist_ok=True)
# exist_ok=True: μ΄λ―Έ μ‘΄μ¬ν΄λ μλ¬ λ°μ μ ν¨
νμΌ μμ±β
# λΉ νμΌ μμ±
with open('new_file.txt', 'w') as f:
pass
# λ΄μ©κ³Ό ν¨κ» νμΌ μμ±
with open('data.txt', 'w', encoding='utf-8') as f:
f.write('Hello, World!\n')
f.write('Python μλν')
νμΌ λ° ν΄λ μμ β
import os
import shutil
# νμΌ μμ
if os.path.exists('file_to_delete.txt'):
os.remove('file_to_delete.txt')
# λΉ λλ ν 리 μμ
if os.path.exists('empty_folder'):
os.rmdir('empty_folder')
# λ΄μ©μ΄ μλ λλ ν 리 μμ
if os.path.exists('folder_with_files'):
shutil.rmtree('folder_with_files')
νμΌ κ²μβ
os.walkλ‘ νμ ν΄λ νμβ
import os
# λͺ¨λ νμ ν΄λμ νμΌ μ°ΎκΈ°
for root, dirs, files in os.walk('/path/to/search'):
for file in files:
if file.endswith('.txt'):
full_path = os.path.join(root, file)
print(full_path)
glob ν¨ν΄ λ§€μΉβ
import glob
# νμ¬ ν΄λμ λͺ¨λ .py νμΌ
python_files = glob.glob('*.py')
# λͺ¨λ νμ ν΄λμ .txt νμΌ
all_txt_files = glob.glob('**/*.txt', recursive=True)
# νΉμ ν¨ν΄μ νμΌ
data_files = glob.glob('data_*.csv')
# pathlibκ³Ό ν¨κ» μ¬μ©
from pathlib import Path
for file in Path('.').rglob('*.log'):
print(file)
νμΌ μ 보 νμΈβ
import os
from datetime import datetime
file_path = 'example.txt'
# νμΌ μ‘΄μ¬ νμΈ
exists = os.path.exists(file_path)
# νμΌμΈμ§ λλ ν 리μΈμ§ νμΈ
is_file = os.path.isfile(file_path)
is_dir = os.path.isdir(file_path)
# νμΌ ν¬κΈ° (λ°μ΄νΈ)
size = os.path.getsize(file_path)
print(f"ν¬κΈ°: {size / 1024:.2f} KB")
# νμΌ μμ μκ°
mtime = os.path.getmtime(file_path)
modified_date = datetime.fromtimestamp(mtime)
print(f"λ§μ§λ§ μμ : {modified_date}")
# νμΌ μμ± μκ°
ctime = os.path.getctime(file_path)
created_date = datetime.fromtimestamp(ctime)
print(f"μμ± μκ°: {created_date}")
μ€μ μμ β
1. μ¬μ§ μ 리 μ€ν¬λ¦½νΈβ
λ μ§λ³λ‘ μ¬μ§μ μλμΌλ‘ λΆλ₯ν©λλ€.
import os
import shutil
from datetime import datetime
from pathlib import Path
def organize_photos(source_dir, dest_dir):
"""μ¬μ§μ λ μ§λ³λ‘ μ 리"""
# λͺ©μ μ§ ν΄λ μμ±
os.makedirs(dest_dir, exist_ok=True)
# μ΄λ―Έμ§ νμ₯μ
image_extensions = {'.jpg', '.jpeg', '.png', '.gif', '.heic'}
for file_path in Path(source_dir).rglob('*'):
if file_path.suffix.lower() in image_extensions:
# νμΌ μμ λ μ§ κ°μ Έμ€κΈ°
mtime = os.path.getmtime(file_path)
date = datetime.fromtimestamp(mtime)
# μ°λ/μ ν΄λ μμ±
year_month = date.strftime('%Y/%m')
target_dir = os.path.join(dest_dir, year_month)
os.makedirs(target_dir, exist_ok=True)
# νμΌ μ΄λ
target_path = os.path.join(target_dir, file_path.name)
# μ€λ³΅ νμΌλͺ
μ²λ¦¬
counter = 1
while os.path.exists(target_path):
name, ext = os.path.splitext(file_path.name)
target_path = os.path.join(
target_dir,
f"{name}_{counter}{ext}"
)
counter += 1
shutil.move(str(file_path), target_path)
print(f"μ΄λ: {file_path.name} -> {year_month}/")
# μ¬μ© μμ
organize_photos('/Users/username/Downloads', '/Users/username/Photos')
2. μλ λ°±μ μ€ν¬λ¦½νΈβ
μ€μν νμΌμ λ μ§λ³λ‘ λ°±μ ν©λλ€.
import os
import shutil
from datetime import datetime
import zipfile
def backup_files(source_dirs, backup_dir):
"""νμΌμ μμΆνμ¬ λ°±μ
"""
# λ°±μ
ν΄λ μμ±
os.makedirs(backup_dir, exist_ok=True)
# λ°±μ
νμΌλͺ
(λ μ§ ν¬ν¨)
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
backup_name = f"backup_{timestamp}.zip"
backup_path = os.path.join(backup_dir, backup_name)
# ZIP νμΌ μμ±
with zipfile.ZipFile(backup_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
for source_dir in source_dirs:
for root, dirs, files in os.walk(source_dir):
for file in files:
file_path = os.path.join(root, file)
# ZIP λ΄ κ²½λ‘ μ€μ
arcname = os.path.relpath(file_path, os.path.dirname(source_dir))
zipf.write(file_path, arcname)
print(f"λ°±μ
: {file_path}")
# νμΌ ν¬κΈ° νμΈ
size_mb = os.path.getsize(backup_path) / (1024 * 1024)
print(f"\nλ°±μ
μλ£: {backup_name} ({size_mb:.2f} MB)")
# μ€λλ λ°±μ
μμ (30κ° μ΄μ μ μ§ μ ν¨)
cleanup_old_backups(backup_dir, keep=30)
def cleanup_old_backups(backup_dir, keep=30):
"""μ€λλ λ°±μ
νμΌ μμ """
backups = []
for file in os.listdir(backup_dir):
if file.startswith('backup_') and file.endswith('.zip'):
file_path = os.path.join(backup_dir, file)
mtime = os.path.getmtime(file_path)
backups.append((mtime, file_path))
# μ΅μ μμΌλ‘ μ λ ¬
backups.sort(reverse=True)
# μ€λλ λ°±μ
μμ
for _, file_path in backups[keep:]:
os.remove(file_path)
print(f"μμ : {os.path.basename(file_path)}")
# μ¬μ© μμ
backup_files(
source_dirs=[
'/Users/username/Documents',
'/Users/username/Projects'
],
backup_dir='/Users/username/Backups'
)
3. λ‘κ·Έ νμΌ μ 리β
μ€λλκ³ ν° λ‘κ·Έ νμΌμ μλμΌλ‘ μ 리ν©λλ€.
import os
import gzip
import shutil
from datetime import datetime, timedelta
def cleanup_logs(log_dir, days_to_keep=7, compress_days=3):
"""λ‘κ·Έ νμΌ μ 리 λ° μμΆ"""
now = datetime.now()
for file in os.listdir(log_dir):
if not file.endswith('.log'):
continue
file_path = os.path.join(log_dir, file)
# νμΌ μμ λ μ§
mtime = datetime.fromtimestamp(os.path.getmtime(file_path))
age = (now - mtime).days
# μ€λλ νμΌ μμ
if age > days_to_keep:
os.remove(file_path)
print(f"μμ : {file} (μμ± ν {age}μΌ)")
# μ€κ° λ μ§ νμΌ μμΆ
elif age > compress_days:
# μ΄λ―Έ μμΆλ νμΌμ μ€ν΅
gz_path = file_path + '.gz'
if os.path.exists(gz_path):
continue
# μμΆ
with open(file_path, 'rb') as f_in:
with gzip.open(gz_path, 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
# μλ³Έ μμ
os.remove(file_path)
# ν¬κΈ° λΉκ΅
original_size = os.path.getsize(file_path)
compressed_size = os.path.getsize(gz_path)
ratio = (1 - compressed_size / original_size) * 100
print(f"μμΆ: {file} (μ©λ {ratio:.1f}% κ°μ)")
# μ¬μ© μμ
cleanup_logs('/var/log/myapp', days_to_keep=7, compress_days=3)
4. νμΌλͺ μΌκ΄ λ³κ²½β
μ¬λ¬ νμΌμ μ΄λ¦μ κ·μΉμ λ°λΌ λ³κ²½ν©λλ€.
import os
import re
def batch_rename(directory, pattern, replacement):
"""μ κ·μ ν¨ν΄μΌλ‘ νμΌλͺ
μΌκ΄ λ³κ²½"""
renamed_count = 0
for filename in os.listdir(directory):
# ν¨ν΄ λ§€μΉ
new_name = re.sub(pattern, replacement, filename)
if new_name != filename:
old_path = os.path.join(directory, filename)
new_path = os.path.join(directory, new_name)
# μ€λ³΅ λ°©μ§
if os.path.exists(new_path):
print(f"건λλ: {filename} (μ΄λ―Έ μ‘΄μ¬ν¨)")
continue
os.rename(old_path, new_path)
print(f"{filename} -> {new_name}")
renamed_count += 1
print(f"\nμ΄ {renamed_count}κ° νμΌλͺ
λ³κ²½ μλ£")
def add_prefix(directory, prefix):
"""λͺ¨λ νμΌμ μ λμ¬ μΆκ°"""
for filename in os.listdir(directory):
old_path = os.path.join(directory, filename)
# λλ ν 리λ μ μΈ
if os.path.isdir(old_path):
continue
new_name = prefix + filename
new_path = os.path.join(directory, new_name)
os.rename(old_path, new_path)
print(f"{filename} -> {new_name}")
def sequential_numbering(directory, prefix='file', start=1):
"""νμΌμ μμ°¨μ μΌλ‘ λ²νΈ λΆμ¬"""
files = [f for f in os.listdir(directory)
if os.path.isfile(os.path.join(directory, f))]
# νμΌ μ λ ¬
files.sort()
for i, filename in enumerate(files, start=start):
# νμ₯μ λΆλ¦¬
_, ext = os.path.splitext(filename)
old_path = os.path.join(directory, filename)
new_name = f"{prefix}_{i:03d}{ext}"
new_path = os.path.join(directory, new_name)
os.rename(old_path, new_path)
print(f"{filename} -> {new_name}")
# μ¬μ© μμ
# 곡백μ μΈλμ€μ½μ΄λ‘ λ³κ²½
batch_rename('/path/to/files', r'\s+', '_')
# λ μ§ νμ λ³κ²½ (2023-01-01 -> 20230101)
batch_rename('/path/to/files', r'(\d{4})-(\d{2})-(\d{2})', r'\1\2\3')
# μ λμ¬ μΆκ°
add_prefix('/path/to/files', 'backup_')
# μμ°¨ λ²νΈ λΆμ¬
sequential_numbering('/path/to/photos', prefix='photo', start=1)