KR_FileIO - somaz94/python-study GitHub Wiki

Python ํŒŒ์ผ ์ž…์ถœ๋ ฅ(File I/O) ๊ฐœ๋… ์ •๋ฆฌ


1๏ธโƒฃ ํŒŒ์ผ ์—ด๊ธฐ/๋‹ซ๊ธฐ

ํŒŒ์ด์ฌ์—์„œ๋Š” open() ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ํŒŒ์ผ์„ ์—ด ์ˆ˜ ์žˆ๋‹ค.

# ๊ธฐ๋ณธ ํŒŒ์ผ ์—ด๊ธฐ/๋‹ซ๊ธฐ
file = open('example.txt', 'w')  # ์“ฐ๊ธฐ ๋ชจ๋“œ๋กœ ํŒŒ์ผ ์—ด๊ธฐ
file.close()                     # ํŒŒ์ผ ๋‹ซ๊ธฐ

# with ๋ฌธ์„ ์‚ฌ์šฉํ•œ ํŒŒ์ผ ์ฒ˜๋ฆฌ (๊ถŒ์žฅ)
with open('example.txt', 'w') as file:
    file.write('Hello, World!')  # ์ž๋™์œผ๋กœ ํŒŒ์ผ์ด ๋‹ซํž˜

# ์ธ์ฝ”๋”ฉ ์ง€์ •
with open('unicode.txt', 'w', encoding='utf-8') as file:
    file.write('์•ˆ๋…•ํ•˜์„ธ์š”!')  # ์œ ๋‹ˆ์ฝ”๋“œ ๋ฌธ์ž ์ฒ˜๋ฆฌ

# ์—๋Ÿฌ ์ฒ˜๋ฆฌ
try:
    with open('nonexistent.txt', 'r') as file:
        content = file.read()
except FileNotFoundError:
    print("ํŒŒ์ผ์ด ์กด์žฌํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.")
except PermissionError:
    print("ํŒŒ์ผ์— ์ ‘๊ทผํ•  ๊ถŒํ•œ์ด ์—†์Šต๋‹ˆ๋‹ค.")
except IOError as e:
    print(f"์ž…์ถœ๋ ฅ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค: {e}")

ํŒŒ์ผ ๋ชจ๋“œ

  • 'r': ์ฝ๊ธฐ ๋ชจ๋“œ (๊ธฐ๋ณธ๊ฐ’) - ํŒŒ์ผ์ด ์—†์œผ๋ฉด ์—๋Ÿฌ ๋ฐœ์ƒ
  • 'w': ์“ฐ๊ธฐ ๋ชจ๋“œ (ํŒŒ์ผ ๋‚ด์šฉ ๋ฎ์–ด์“ฐ๊ธฐ) - ํŒŒ์ผ์ด ์—†์œผ๋ฉด ์ƒˆ๋กœ ์ƒ์„ฑ
  • 'a': ์ถ”๊ฐ€ ๋ชจ๋“œ (ํŒŒ์ผ ๋์— ๋‚ด์šฉ ์ถ”๊ฐ€) - ํŒŒ์ผ์ด ์—†์œผ๋ฉด ์ƒˆ๋กœ ์ƒ์„ฑ
  • 'x': ๋ฐฐํƒ€์  ์ƒ์„ฑ ๋ชจ๋“œ - ํŒŒ์ผ์ด ์ด๋ฏธ ์žˆ์œผ๋ฉด ์—๋Ÿฌ ๋ฐœ์ƒ
  • 'b': ๋ฐ”์ด๋„ˆ๋ฆฌ ๋ชจ๋“œ (ํ…์ŠคํŠธ๊ฐ€ ์•„๋‹Œ ๋ฐ”์ด๋„ˆ๋ฆฌ ๋ฐ์ดํ„ฐ ์ฒ˜๋ฆฌ)
  • 't': ํ…์ŠคํŠธ ๋ชจ๋“œ (๊ธฐ๋ณธ๊ฐ’)
  • '+': ์ฝ๊ธฐ/์“ฐ๊ธฐ ๋ชจ๋“œ (์˜ˆ: 'r+', 'w+', 'a+')
# ๊ฐ ๋ชจ๋“œ ์˜ˆ์‹œ
with open('file.txt', 'r') as f:       # ์ฝ๊ธฐ ์ „์šฉ
    content = f.read()

with open('file.txt', 'w') as f:       # ์“ฐ๊ธฐ ์ „์šฉ (๋ฎ์–ด์“ฐ๊ธฐ)
    f.write('์ƒˆ๋กœ์šด ๋‚ด์šฉ')

with open('file.txt', 'a') as f:       # ์ถ”๊ฐ€ ๋ชจ๋“œ
    f.write('๊ธฐ์กด ๋‚ด์šฉ์— ์ถ”๊ฐ€')

try:
    with open('new_file.txt', 'x') as f:  # ๋ฐฐํƒ€์  ์ƒ์„ฑ
        f.write('์ƒˆ ํŒŒ์ผ ๋‚ด์šฉ')
except FileExistsError:
    print("ํŒŒ์ผ์ด ์ด๋ฏธ ์กด์žฌํ•ฉ๋‹ˆ๋‹ค")

with open('binary.dat', 'wb') as f:    # ๋ฐ”์ด๋„ˆ๋ฆฌ ์“ฐ๊ธฐ
    f.write(b'\x00\x01\x02\x03')

with open('file.txt', 'r+') as f:      # ์ฝ๊ธฐ+์“ฐ๊ธฐ
    content = f.read()
    f.write('๋” ๋งŽ์€ ๋‚ด์šฉ')


2๏ธโƒฃ ํŒŒ์ผ ์“ฐ๊ธฐ

# ๋‹จ์ˆœ ํ…์ŠคํŠธ ์“ฐ๊ธฐ
with open('test.txt', 'w', encoding='utf-8') as f:
    f.write('Hello\n')
    f.write('World\n')

# print() ํ•จ์ˆ˜๋กœ ํŒŒ์ผ์— ์“ฐ๊ธฐ
with open('test.txt', 'w', encoding='utf-8') as f:
    print('Hello', file=f)
    print('World', file=f)
    print('์•ˆ๋…•ํ•˜์„ธ์š”', '๋ฐ˜๊ฐ‘์Šต๋‹ˆ๋‹ค', sep=', ', file=f)

# ๋ฆฌ์ŠคํŠธ์˜ ๋‚ด์šฉ์„ ํŒŒ์ผ์— ์“ฐ๊ธฐ
lines = ['Line 1', 'Line 2', 'Line 3']
with open('test.txt', 'w', encoding='utf-8') as f:
    f.writelines(line + '\n' for line in lines)

# ๋”•์…”๋„ˆ๋ฆฌ ๋ฐ์ดํ„ฐ ์“ฐ๊ธฐ
data = {'name': 'ํ™๊ธธ๋™', 'age': 30, 'city': '์„œ์šธ'}
with open('data.txt', 'w', encoding='utf-8') as f:
    for key, value in data.items():
        f.write(f"{key}: {value}\n")

# ์ถ”๊ฐ€ ๋ชจ๋“œ๋กœ ํŒŒ์ผ์— ๋‚ด์šฉ ์ถ”๊ฐ€
with open('log.txt', 'a', encoding='utf-8') as f:
    import datetime
    now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    f.write(f"[{now}] ๋กœ๊ทธ ํ•ญ๋ชฉ ์ถ”๊ฐ€\n")

ํŒŒ์ผ ์œ„์น˜ ์ œ์–ด

# ํŒŒ์ผ ์“ฐ๊ธฐ ์œ„์น˜ ์ œ์–ด
with open('position.txt', 'w+', encoding='utf-8') as f:
    f.write("์ฒซ ๋ฒˆ์งธ ์ค„\n")
    f.write("๋‘ ๋ฒˆ์งธ ์ค„\n")
    
    position = f.tell()  # ํ˜„์žฌ ์œ„์น˜ ์ €์žฅ
    print(f"ํ˜„์žฌ ์œ„์น˜: {position} ๋ฐ”์ดํŠธ")
    
    f.seek(0)  # ํŒŒ์ผ์˜ ์ฒ˜์Œ์œผ๋กœ ์ด๋™
    f.write("๋ฎ์–ด์“ด ์ฒซ ๋ฒˆ์งธ ์ค„\n")  # ์ฒซ ์ค„ ๋ฎ์–ด์“ฐ๊ธฐ
    
    f.seek(0, 2)  # ํŒŒ์ผ์˜ ๋์œผ๋กœ ์ด๋™ (0์€ ์œ„์น˜, 2๋Š” ํŒŒ์ผ ๋ ๊ธฐ์ค€)
    f.write("์„ธ ๋ฒˆ์งธ ์ค„\n")


3๏ธโƒฃ ํŒŒ์ผ ์ฝ๊ธฐ

# ์ „์ฒด ๋‚ด์šฉ ์ฝ๊ธฐ
with open('test.txt', 'r', encoding='utf-8') as f:
    content = f.read()
    print(content)

# ํŠน์ • ํฌ๊ธฐ๋งŒํผ ์ฝ๊ธฐ
with open('test.txt', 'r', encoding='utf-8') as f:
    chunk = f.read(10)  # ์ฒ˜์Œ 10๋ฐ”์ดํŠธ๋งŒ ์ฝ๊ธฐ
    print(chunk)
    
    next_chunk = f.read(10)  # ๋‹ค์Œ 10๋ฐ”์ดํŠธ ์ฝ๊ธฐ
    print(next_chunk)

# ํ•œ ์ค„์”ฉ ์ฝ๊ธฐ
with open('test.txt', 'r', encoding='utf-8') as f:
    line = f.readline()  # ์ฒซ ๋ฒˆ์งธ ์ค„
    print(line, end='')  # ์ค„๋ฐ”๊ฟˆ ๋ฌธ์ž๊ฐ€ ์ด๋ฏธ ํฌํ•จ๋˜์–ด ์žˆ์Œ
    
    second_line = f.readline()  # ๋‘ ๋ฒˆ์งธ ์ค„
    print(second_line, end='')

# ๋ชจ๋“  ์ค„์„ ๋ฆฌ์ŠคํŠธ๋กœ ์ฝ๊ธฐ
with open('test.txt', 'r', encoding='utf-8') as f:
    lines = f.readlines()
    print(f"ํŒŒ์ผ์˜ ์ด ์ค„ ์ˆ˜: {len(lines)}")
    
    for i, line in enumerate(lines, 1):
        print(f"์ค„ {i}: {line.strip()}")  # strip()์œผ๋กœ ์ค„๋ฐ”๊ฟˆ ์ œ๊ฑฐ

# for ๋ฌธ์œผ๋กœ ํŒŒ์ผ ์ฝ๊ธฐ (๋ฉ”๋ชจ๋ฆฌ ํšจ์œจ์ )
with open('test.txt', 'r', encoding='utf-8') as f:
    for line in f:  # ํŒŒ์ผ ๊ฐ์ฒด๋Š” ์ดํ„ฐ๋Ÿฌ๋ธ”ํ•˜์—ฌ ํ•œ ์ค„์”ฉ ์ˆœํšŒ
        print(line.strip())

# ์œ„์น˜ ์ง€์ •ํ•˜์—ฌ ์ฝ๊ธฐ
with open('test.txt', 'r', encoding='utf-8') as f:
    f.seek(10)  # 10๋ฒˆ์งธ ๋ฐ”์ดํŠธ๋กœ ์ด๋™
    partial = f.read(20)  # 20๋ฐ”์ดํŠธ ์ฝ๊ธฐ
    print(partial)

๋Œ€์šฉ๋Ÿ‰ ํŒŒ์ผ ์ฒ˜๋ฆฌ

# ํฐ ํŒŒ์ผ ํšจ์œจ์ ์œผ๋กœ ์ฒ˜๋ฆฌ
def count_lines(filename):
    count = 0
    with open(filename, 'r', encoding='utf-8') as f:
        for _ in f:
            count += 1
    return count

# ์ฒญํฌ ๋‹จ์œ„๋กœ ํŒŒ์ผ ์ฝ๊ธฐ
def read_in_chunks(filename, chunk_size=1024):
    """์ง€์ •๋œ ํฌ๊ธฐ์˜ ์ฒญํฌ ๋‹จ์œ„๋กœ ํŒŒ์ผ ์ฝ๊ธฐ"""
    with open(filename, 'rb') as f:  # ๋ฐ”์ด๋„ˆ๋ฆฌ ๋ชจ๋“œ ์‚ฌ์šฉ
        while True:
            chunk = f.read(chunk_size)
            if not chunk:  # ํŒŒ์ผ ๋์— ๋„๋‹ฌ
                break
            yield chunk

# ์‚ฌ์šฉ ์˜ˆ์‹œ
# for chunk in read_in_chunks('large_file.txt'):
#     process_data(chunk)


4๏ธโƒฃ ํŒŒ์ผ ๊ด€๋ฆฌ

import os
import shutil

# ํŒŒ์ผ ์กด์žฌ ์—ฌ๋ถ€ ํ™•์ธ
if os.path.exists('test.txt'):
    print('ํŒŒ์ผ์ด ์กด์žฌํ•ฉ๋‹ˆ๋‹ค')
else:
    print('ํŒŒ์ผ์ด ์กด์žฌํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค')

# ํŒŒ์ผ์ธ์ง€ ๋””๋ ‰ํ† ๋ฆฌ์ธ์ง€ ํ™•์ธ
if os.path.isfile('test.txt'):
    print('test.txt๋Š” ํŒŒ์ผ์ž…๋‹ˆ๋‹ค')
elif os.path.isdir('test_dir'):
    print('test_dir์€ ๋””๋ ‰ํ† ๋ฆฌ์ž…๋‹ˆ๋‹ค')

# ํŒŒ์ผ ์ •๋ณด ํ™•์ธ
if os.path.exists('test.txt'):
    size = os.path.getsize('test.txt')  # ํŒŒ์ผ ํฌ๊ธฐ(๋ฐ”์ดํŠธ)
    mtime = os.path.getmtime('test.txt')  # ์ˆ˜์ • ์‹œ๊ฐ„ (Unix ํƒ€์ž„์Šคํƒฌํ”„)
    import datetime
    mod_time = datetime.datetime.fromtimestamp(mtime)
    print(f"ํŒŒ์ผ ํฌ๊ธฐ: {size} ๋ฐ”์ดํŠธ")
    print(f"์ตœ์ข… ์ˆ˜์ • ์‹œ๊ฐ„: {mod_time}")

# ํŒŒ์ผ ์‚ญ์ œ
if os.path.exists('temp.txt'):
    os.remove('temp.txt')
    print('ํŒŒ์ผ์ด ์‚ญ์ œ๋˜์—ˆ์Šต๋‹ˆ๋‹ค')

# ํŒŒ์ผ ์ด๋ฆ„ ๋ณ€๊ฒฝ
if os.path.exists('old.txt'):
os.rename('old.txt', 'new.txt')
    print('ํŒŒ์ผ ์ด๋ฆ„์ด ๋ณ€๊ฒฝ๋˜์—ˆ์Šต๋‹ˆ๋‹ค')

# ํŒŒ์ผ ๋ณต์‚ฌ
import shutil
if os.path.exists('source.txt'):
    shutil.copy('source.txt', 'destination.txt')  # ํŒŒ์ผ ๋ณต์‚ฌ
    shutil.copy2('source.txt', 'destination2.txt')  # ๋ฉ”ํƒ€๋ฐ์ดํ„ฐ ํฌํ•จ ๋ณต์‚ฌ

# ๋””๋ ‰ํ† ๋ฆฌ ์ƒ์„ฑ
if not os.path.exists('new_directory'):
    os.makedirs('new_directory', exist_ok=True)  # ์ค‘์ฒฉ ๋””๋ ‰ํ† ๋ฆฌ ์ƒ์„ฑ
    print('๋””๋ ‰ํ† ๋ฆฌ๊ฐ€ ์ƒ์„ฑ๋˜์—ˆ์Šต๋‹ˆ๋‹ค')

# ๋””๋ ‰ํ† ๋ฆฌ ์‚ญ์ œ
if os.path.exists('empty_dir') and os.path.isdir('empty_dir'):
    os.rmdir('empty_dir')  # ๋นˆ ๋””๋ ‰ํ† ๋ฆฌ๋งŒ ์‚ญ์ œ ๊ฐ€๋Šฅ
    print('๋นˆ ๋””๋ ‰ํ† ๋ฆฌ๊ฐ€ ์‚ญ์ œ๋˜์—ˆ์Šต๋‹ˆ๋‹ค')

# ๋””๋ ‰ํ† ๋ฆฌ์™€ ๋‚ด์šฉ ๋ชจ๋‘ ์‚ญ์ œ
if os.path.exists('dir_with_files') and os.path.isdir('dir_with_files'):
    shutil.rmtree('dir_with_files')
    print('๋””๋ ‰ํ† ๋ฆฌ์™€ ๋‚ด์šฉ์ด ๋ชจ๋‘ ์‚ญ์ œ๋˜์—ˆ์Šต๋‹ˆ๋‹ค')

# ํŒŒ์ผ ๊ฒฝ๋กœ ๋‹ค๋ฃจ๊ธฐ
filename = 'document.txt'
directory = 'projects/python'
full_path = os.path.join(directory, filename)  # 'projects/python/document.txt'
print(f"์ „์ฒด ๊ฒฝ๋กœ: {full_path}")

# ๊ฒฝ๋กœ ๋ถ„ํ•ด
path = '/home/user/documents/report.pdf'
dirname = os.path.dirname(path)    # '/home/user/documents'
basename = os.path.basename(path)  # 'report.pdf'
filename, ext = os.path.splitext(basename)  # ('report', '.pdf')
print(f"๋””๋ ‰ํ† ๋ฆฌ: {dirname}")
print(f"ํŒŒ์ผ๋ช…: {filename}, ํ™•์žฅ์ž: {ext}")


5๏ธโƒฃ ํŠน์ˆ˜ ํŒŒ์ผ ํ˜•์‹ ์ฒ˜๋ฆฌ

CSV ํŒŒ์ผ

import csv

# CSV ํŒŒ์ผ ์“ฐ๊ธฐ
data = [
    ['์ด๋ฆ„', '๋‚˜์ด', '์ง์—…'],
    ['๊น€์ฒ ์ˆ˜', 28, '๊ฐœ๋ฐœ์ž'],
    ['์ด์˜ํฌ', 32, '๋””์ž์ด๋„ˆ'],
    ['๋ฐ•์ง€๋ฏผ', 24, 'ํ•™์ƒ']
]

with open('people.csv', 'w', newline='', encoding='utf-8') as f:
    writer = csv.writer(f)
    writer.writerows(data)  # ๋ชจ๋“  ํ–‰ ํ•œ ๋ฒˆ์— ์“ฐ๊ธฐ

# CSV ํŒŒ์ผ ์ฝ๊ธฐ
with open('people.csv', 'r', encoding='utf-8') as f:
    reader = csv.reader(f)
    header = next(reader)  # ํ—ค๋” ํ–‰ ์ฝ๊ธฐ
    print(f"ํ—ค๋”: {header}")
    
    for row in reader:
        print(f"{row[0]}๋Š” {row[1]}์„ธ {row[2]}์ž…๋‹ˆ๋‹ค.")

# ๋”•์…”๋„ˆ๋ฆฌ๋กœ CSV ๋‹ค๋ฃจ๊ธฐ
dict_data = [
    {'์ด๋ฆ„': '๊น€์ฒ ์ˆ˜', '๋‚˜์ด': 28, '์ง์—…': '๊ฐœ๋ฐœ์ž'},
    {'์ด๋ฆ„': '์ด์˜ํฌ', '๋‚˜์ด': 32, '์ง์—…': '๋””์ž์ด๋„ˆ'},
    {'์ด๋ฆ„': '๋ฐ•์ง€๋ฏผ', '๋‚˜์ด': 24, '์ง์—…': 'ํ•™์ƒ'}
]

with open('people_dict.csv', 'w', newline='', encoding='utf-8') as f:
    fieldnames = ['์ด๋ฆ„', '๋‚˜์ด', '์ง์—…']
    writer = csv.DictWriter(f, fieldnames=fieldnames)
    
    writer.writeheader()  # ํ—ค๋” ์“ฐ๊ธฐ
    writer.writerows(dict_data)  # ๋”•์…”๋„ˆ๋ฆฌ ๋ชฉ๋ก ์“ฐ๊ธฐ

# ๋”•์…”๋„ˆ๋ฆฌ๋กœ CSV ์ฝ๊ธฐ
with open('people_dict.csv', 'r', encoding='utf-8') as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(f"{row['์ด๋ฆ„']}๋Š” {row['๋‚˜์ด']}์„ธ {row['์ง์—…']}์ž…๋‹ˆ๋‹ค.")

JSON ํŒŒ์ผ

import json

# JSON ํŒŒ์ผ ์“ฐ๊ธฐ
data = {
    'name': 'ํ™๊ธธ๋™',
    'age': 30,
    'city': '์„œ์šธ',
    'hobbies': ['๋…์„œ', '๋“ฑ์‚ฐ', 'ํ”„๋กœ๊ทธ๋ž˜๋ฐ'],
    'active': True,
    'scores': {
        'math': 85,
        'english': 92,
        'python': 98
    }
}

with open('data.json', 'w', encoding='utf-8') as f:
    json.dump(data, f, ensure_ascii=False, indent=4)
    # ensure_ascii=False: ํ•œ๊ธ€ ๋“ฑ ์œ ๋‹ˆ์ฝ”๋“œ ๋ฌธ์ž ๊ทธ๋Œ€๋กœ ์ €์žฅ
    # indent=4: ๋“ค์—ฌ์“ฐ๊ธฐ๋กœ ๊ฐ€๋…์„ฑ ํ–ฅ์ƒ

# JSON ํŒŒ์ผ ์ฝ๊ธฐ
with open('data.json', 'r', encoding='utf-8') as f:
    loaded_data = json.load(f)
    print(f"์ด๋ฆ„: {loaded_data['name']}")
    print(f"์ทจ๋ฏธ: {', '.join(loaded_data['hobbies'])}")
    print(f"ํŒŒ์ด์ฌ ์ ์ˆ˜: {loaded_data['scores']['python']}")

# JSON ๋ฌธ์ž์—ด ๋‹ค๋ฃจ๊ธฐ
json_str = json.dumps(data, ensure_ascii=False)
print(json_str)

parsed_data = json.loads(json_str)
print(parsed_data['city'])

๋ฐ”์ด๋„ˆ๋ฆฌ ํŒŒ์ผ

# ๋ฐ”์ด๋„ˆ๋ฆฌ ํŒŒ์ผ ์“ฐ๊ธฐ
with open('binary.dat', 'wb') as f:
    f.write(b'\x48\x65\x6c\x6c\x6f')  # 'Hello'์˜ ๋ฐ”์ดํŠธ ํ‘œํ˜„

# ๋ฐ”์ด๋„ˆ๋ฆฌ ํŒŒ์ผ ์ฝ๊ธฐ
with open('binary.dat', 'rb') as f:
    data = f.read()
    print(data)  # b'Hello'
    print(data.decode('utf-8'))  # 'Hello'

# ๊ตฌ์กฐํ™”๋œ ๋ฐ”์ด๋„ˆ๋ฆฌ ๋ฐ์ดํ„ฐ
import struct

# ์ •์ˆ˜์™€ ๋ฌธ์ž์—ด ํŒจํ‚น
with open('packed.bin', 'wb') as f:
    # 'i'๋Š” 4๋ฐ”์ดํŠธ ์ •์ˆ˜, '5s'๋Š” 5๋ฐ”์ดํŠธ ๋ฌธ์ž์—ด
    packed_data = struct.pack('i5s', 42, b'Hello')
    f.write(packed_data)

# ์–ธํŒจํ‚น
with open('packed.bin', 'rb') as f:
    data = f.read()
    unpacked = struct.unpack('i5s', data)
    print(f"์ •์ˆ˜: {unpacked[0]}, ๋ฌธ์ž์—ด: {unpacked[1].decode('utf-8')}")

# ์ด๋ฏธ์ง€ ํŒŒ์ผ ์ฒ˜๋ฆฌ ์˜ˆ์‹œ
def copy_image(src, dst):
    """์ด๋ฏธ์ง€ ํŒŒ์ผ์„ ๋ณต์‚ฌํ•˜๋Š” ํ•จ์ˆ˜"""
    with open(src, 'rb') as src_file:
        with open(dst, 'wb') as dst_file:
            dst_file.write(src_file.read())

# copy_image('source.jpg', 'copy.jpg')


6๏ธโƒฃ ํŒŒ์ผ ์‹œ์Šคํ…œ ํƒ์ƒ‰

import os

# ํ˜„์žฌ ์ž‘์—… ๋””๋ ‰ํ† ๋ฆฌ ํ™•์ธ
current_dir = os.getcwd()
print(f"ํ˜„์žฌ ๋””๋ ‰ํ† ๋ฆฌ: {current_dir}")

# ๋””๋ ‰ํ† ๋ฆฌ ๋ณ€๊ฒฝ
# os.chdir('../')  # ์ƒ์œ„ ๋””๋ ‰ํ† ๋ฆฌ๋กœ ์ด๋™
# print(f"๋ณ€๊ฒฝ๋œ ๋””๋ ‰ํ† ๋ฆฌ: {os.getcwd()}")

# ๋””๋ ‰ํ† ๋ฆฌ ๋‚ด์šฉ ๋‚˜์—ด
entries = os.listdir('.')  # ํ˜„์žฌ ๋””๋ ‰ํ† ๋ฆฌ ๋‚ด์šฉ
print("ํ˜„์žฌ ๋””๋ ‰ํ† ๋ฆฌ ๋‚ด์šฉ:")
for entry in entries:
    if os.path.isfile(entry):
        print(f"ํŒŒ์ผ: {entry}")
    elif os.path.isdir(entry):
        print(f"๋””๋ ‰ํ† ๋ฆฌ: {entry}")

# ํŠน์ • ํ™•์žฅ์ž ํŒŒ์ผ ์ฐพ๊ธฐ
def find_files_by_extension(directory, extension):
    """์ง€์ •๋œ ๋””๋ ‰ํ† ๋ฆฌ์—์„œ ํŠน์ • ํ™•์žฅ์ž๋ฅผ ๊ฐ€์ง„ ํŒŒ์ผ ์ฐพ๊ธฐ"""
    result = []
    for entry in os.listdir(directory):
        full_path = os.path.join(directory, entry)
        if os.path.isfile(full_path) and entry.endswith(extension):
            result.append(full_path)
    return result

# ์žฌ๊ท€์ ์œผ๋กœ ๋””๋ ‰ํ† ๋ฆฌ ํƒ์ƒ‰
def list_all_files(directory):
    """๋””๋ ‰ํ† ๋ฆฌ ๋‚ด์˜ ๋ชจ๋“  ํŒŒ์ผ์„ ์žฌ๊ท€์ ์œผ๋กœ ๋‚˜์—ด"""
    for root, dirs, files in os.walk(directory):
        for file in files:
            full_path = os.path.join(root, file)
            print(full_path)

# ํŠน์ • ํŒจํ„ด์˜ ํŒŒ์ผ ์ฐพ๊ธฐ
import glob
python_files = glob.glob('*.py')  # ํ˜„์žฌ ๋””๋ ‰ํ† ๋ฆฌ์˜ ๋ชจ๋“  .py ํŒŒ์ผ
print("Python ํŒŒ์ผ:")
for file in python_files:
    print(file)

# ์žฌ๊ท€์ ์œผ๋กœ ํŠน์ • ํŒจํ„ด ์ฐพ๊ธฐ
all_python_files = glob.glob('**/*.py', recursive=True)
print("๋ชจ๋“  ํ•˜์œ„ ๋””๋ ‰ํ† ๋ฆฌ์˜ Python ํŒŒ์ผ:")
for file in all_python_files:
    print(file)

์ฃผ์š” ํŒ

โœ… ํŒŒ์ผ ์ฒ˜๋ฆฌ ๋ชจ๋ฒ” ์‚ฌ๋ก€:

  • ํ•ญ์ƒ with ๋ฌธ ์‚ฌ์šฉํ•˜์—ฌ ํŒŒ์ผ์„ ์ž๋™์œผ๋กœ ๋‹ซํžˆ๊ฒŒ ํ•œ๋‹ค
  • ํ…์ŠคํŠธ ํŒŒ์ผ ์ฒ˜๋ฆฌ ์‹œ ํ•ญ์ƒ ์ธ์ฝ”๋”ฉ์„ ๋ช…์‹œํ•œ๋‹ค (์ฃผ๋กœ 'utf-8')
  • ํ•œ๊ธ€ ๋“ฑ ์œ ๋‹ˆ์ฝ”๋“œ ์ฒ˜๋ฆฌ ์‹œ encoding='utf-8' ์‚ฌ์šฉ์ด ํ•„์ˆ˜์ ์ด๋‹ค
  • ์ ์ ˆํ•œ ์˜ˆ์™ธ ์ฒ˜๋ฆฌ๋กœ ํŒŒ์ผ ์ ‘๊ทผ ์˜ค๋ฅ˜์— ๋Œ€์‘ํ•œ๋‹ค
  • ํŒŒ์ผ ๊ฒฝ๋กœ๋Š” ๋ฌธ์ž์—ด ์—ฐ๊ฒฐ์ด ์•„๋‹Œ os.path.join() ์‚ฌ์šฉ์„ ๊ถŒ์žฅํ•œ๋‹ค
  • ํฐ ํŒŒ์ผ์€ ํ•œ ๋ฒˆ์— ๋ชจ๋‘ ์ฝ์ง€ ๋ง๊ณ  ํ•œ ์ค„์”ฉ ๋˜๋Š” ์ฒญํฌ ๋‹จ์œ„๋กœ ์ฒ˜๋ฆฌํ•œ๋‹ค
  • CSV, JSON ๋“ฑ ํŠน์ˆ˜ ํ˜•์‹์€ ์ „์šฉ ๋ชจ๋“ˆ์„ ํ™œ์šฉํ•œ๋‹ค
  • os.path ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•ด ๊ฒฝ๋กœ๋ฅผ ์•ˆ์ „ํ•˜๊ฒŒ ๋‹ค๋ฃฌ๋‹ค
  • ๋ฐ”์ด๋„ˆ๋ฆฌ ๋ฐ์ดํ„ฐ๋Š” ํ•ญ์ƒ ๋ฐ”์ด๋„ˆ๋ฆฌ ๋ชจ๋“œ('rb', 'wb')๋กœ ์ฒ˜๋ฆฌํ•œ๋‹ค
  • ํŒŒ์ผ ์ด๋ฆ„์— ๋ณ€์ˆ˜๊ฐ€ ํฌํ•จ๋œ ๊ฒฝ์šฐ f-string ๋ณด๋‹ค๋Š” os.path.join()์„ ์‚ฌ์šฉํ•œ๋‹ค


โš ๏ธ **GitHub.com Fallback** โš ๏ธ