KR_InputOutput - somaz94/python-study GitHub Wiki

Python ์ž…์ถœ๋ ฅ(Input/Output) ๊ฐœ๋… ์ •๋ฆฌ


1๏ธโƒฃ ์‚ฌ์šฉ์ž ์ž…๋ ฅ (Input)

ํŒŒ์ด์ฌ์—์„œ๋Š” input() ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์‚ฌ์šฉ์ž๋กœ๋ถ€ํ„ฐ ์ž…๋ ฅ์„ ๋ฐ›์„ ์ˆ˜ ์žˆ๋‹ค.

# ๊ธฐ๋ณธ ์ž…๋ ฅ
name = input()

# ํ”„๋กฌํ”„ํŠธ์™€ ํ•จ๊ป˜ ์ž…๋ ฅ ๋ฐ›๊ธฐ
age = input("๋‚˜์ด๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”: ")

# ์ˆซ์ž ์ž…๋ ฅ ๋ฐ›๊ธฐ (๋ฌธ์ž์—ด์„ ์ˆซ์ž๋กœ ๋ณ€ํ™˜)
number = int(input("์ˆซ์ž๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”: "))
float_number = float(input("์‹ค์ˆ˜๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”: "))

# ์—ฌ๋Ÿฌ ๊ฐ’ ํ•œ๋ฒˆ์— ์ž…๋ ฅ ๋ฐ›๊ธฐ (๊ณต๋ฐฑ์œผ๋กœ ๊ตฌ๋ถ„)
x, y = map(int, input("๋‘ ์ •์ˆ˜๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”: ").split())
print(f"์ž…๋ ฅํ•œ ๋‘ ์ˆ˜์˜ ํ•ฉ: {x + y}")

# ์—ฌ๋Ÿฌ ๊ฐ’ ํ•œ๋ฒˆ์— ์ž…๋ ฅ ๋ฐ›๊ธฐ (์‰ผํ‘œ๋กœ ๊ตฌ๋ถ„)
a, b, c = map(float, input("์„ธ ์‹ค์ˆ˜๋ฅผ ์‰ผํ‘œ๋กœ ๊ตฌ๋ถ„ํ•˜์—ฌ ์ž…๋ ฅํ•˜์„ธ์š”: ").split(','))
print(f"ํ‰๊ท : {(a + b + c) / 3}")

# ๋ฆฌ์ŠคํŠธ๋กœ ์—ฌ๋Ÿฌ ๊ฐ’ ์ž…๋ ฅ ๋ฐ›๊ธฐ
numbers = list(map(int, input("์—ฌ๋Ÿฌ ์ˆซ์ž๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”: ").split()))
print(f"์ž…๋ ฅํ•œ ์ˆซ์ž๋“ค: {numbers}")
print(f"ํ•ฉ๊ณ„: {sum(numbers)}")

โš ๏ธ ์ฃผ์˜์‚ฌํ•ญ:

  • input()์€ ํ•ญ์ƒ ๋ฌธ์ž์—ด(string)์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค
  • ์ˆซ์ž๋ฅผ ์ž…๋ ฅ๋ฐ›์„ ๋•Œ๋Š” int() ๋˜๋Š” float()๋กœ ๋ณ€ํ™˜์ด ํ•„์š”ํ•˜๋‹ค
  • ์ž˜๋ชป๋œ ํ˜•์‹ ์ž…๋ ฅ ์‹œ ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ์œผ๋ฏ€๋กœ ์˜ˆ์™ธ ์ฒ˜๋ฆฌ๊ฐ€ ๊ถŒ์žฅ๋œ๋‹ค

์ž…๋ ฅ ๊ฒ€์ฆ๊ณผ ์˜ˆ์™ธ ์ฒ˜๋ฆฌ

# ์ˆซ์ž ์ž…๋ ฅ ๊ฒ€์ฆ
while True:
    try:
        age = int(input("๋‚˜์ด๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”: "))
        if age < 0 or age > 150:
            print("์œ ํšจํ•œ ๋‚˜์ด ๋ฒ”์œ„๊ฐ€ ์•„๋‹™๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•˜์„ธ์š”.")
            continue
        break
    except ValueError:
        print("์ˆซ์ž๋งŒ ์ž…๋ ฅํ•˜์„ธ์š”.")

print(f"์ž…๋ ฅํ•œ ๋‚˜์ด: {age}")

# ์„ ํƒ์ง€ ์ž…๋ ฅ ๊ฒ€์ฆ
valid_options = ['A', 'B', 'C']
while True:
    choice = input(f"์˜ต์…˜์„ ์„ ํƒํ•˜์„ธ์š” ({'/'.join(valid_options)}): ").upper()
    if choice in valid_options:
        break
    print("์œ ํšจํ•˜์ง€ ์•Š์€ ์˜ต์…˜์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•˜์„ธ์š”.")

print(f"์„ ํƒํ•œ ์˜ต์…˜: {choice}")

2๏ธโƒฃ ์ถœ๋ ฅ (Print)

1. ๊ธฐ๋ณธ ์ถœ๋ ฅ

# ๋‹จ์ˆœ ์ถœ๋ ฅ
print("Hello, World!")

# ๋ณ€์ˆ˜ ์ถœ๋ ฅ
name = "Alice"
age = 25
print(name, age)

# ๊ตฌ๋ถ„์ž(sep) ์ง€์ •
print("Hello", "World", sep="-")  # Hello-World

# ๋๋ฌธ์ž(end) ์ง€์ •
print("Hello", end="! ")  # Hello! 
print("World")  # World

# ์—ฌ๋Ÿฌ ์ค„ ์ถœ๋ ฅ
print("""
์ฒซ ๋ฒˆ์งธ ์ค„
๋‘ ๋ฒˆ์งธ ์ค„
์„ธ ๋ฒˆ์งธ ์ค„
""")

# ๋ณ€์ˆ˜์™€ ํ…์ŠคํŠธ ํ•จ๊ป˜ ์ถœ๋ ฅ
print("์ด๋ฆ„:", name, "๋‚˜์ด:", age)

2. ๋ฌธ์ž์—ด ํฌ๋งทํŒ…

name = "Alice"
age = 25
height = 165.5

# 1. % ์—ฐ์‚ฐ์ž ์‚ฌ์šฉ (์˜ค๋ž˜๋œ ๋ฐฉ์‹)
print("์ด๋ฆ„: %s, ๋‚˜์ด: %d, ํ‚ค: %.1f" % (name, age, height))

# 2. format() ๋ฉ”์„œ๋“œ ์‚ฌ์šฉ
print("์ด๋ฆ„: {}, ๋‚˜์ด: {}, ํ‚ค: {:.1f}".format(name, age, height))

# ์ธ๋ฑ์Šค ์ง€์ •
print("์ด๋ฆ„: {0}, ๋‚˜์ด: {1}, ํ‚ค: {2:.1f}".format(name, age, height))
print("๋‚˜์ด: {1}, ์ด๋ฆ„: {0}, ํ‚ค: {2:.1f}".format(name, age, height))

# ์ด๋ฆ„ ์ง€์ •
print("์ด๋ฆ„: {n}, ๋‚˜์ด: {a}, ํ‚ค: {h:.1f}".format(n=name, a=age, h=height))

# 3. f-string (Python 3.6+, ๊ฐ€์žฅ ๊ถŒ์žฅ๋จ)
print(f"์ด๋ฆ„: {name}, ๋‚˜์ด: {age}, ํ‚ค: {height:.1f}")

# f-string ๋‚ด ํ‘œํ˜„์‹ ์‚ฌ์šฉ
print(f"๋‚ด๋…„ ๋‚˜์ด: {age + 1}")
print(f"์ธ์น˜ ๋‹จ์œ„ ํ‚ค: {height / 2.54:.2f}inch")

# f-string ๋‚ด ๋”•์…”๋„ˆ๋ฆฌ ์‚ฌ์šฉ
person = {'name': 'Bob', 'age': 30}
print(f"์ด๋ฆ„: {person['name']}, ๋‚˜์ด: {person['age']}")

# ์ •๋ ฌ ๋ฐ ์ฑ„์›€ ๋ฌธ์ž
print(f"{'์™ผ์ชฝ ์ •๋ ฌ':<15}|")  # ์™ผ์ชฝ ์ •๋ ฌ      |
print(f"{'์˜ค๋ฅธ์ชฝ ์ •๋ ฌ':>15}|")  #     ์˜ค๋ฅธ์ชฝ ์ •๋ ฌ|
print(f"{'๊ฐ€์šด๋ฐ ์ •๋ ฌ':^15}|")  #   ๊ฐ€์šด๋ฐ ์ •๋ ฌ  |
print(f"{'0์œผ๋กœ ์ฑ„์›€':0>15}|")  # 00000000000์œผ๋กœ ์ฑ„์›€|

# ์ฒœ ๋‹จ์œ„ ๊ตฌ๋ถ„๊ธฐํ˜ธ
amount = 1234567890
print(f"๊ธˆ์•ก: {amount:,}")  # ๊ธˆ์•ก: 1,234,567,890

3. ์ถœ๋ ฅ ์„œ์‹ ์ง€์ •

# 10์ง„์ˆ˜ (๊ธฐ๋ณธ)
print(f"{42}")  # 42

# 2์ง„์ˆ˜
print(f"{42:b}")  # 101010

# 8์ง„์ˆ˜
print(f"{42:o}")  # 52

# 16์ง„์ˆ˜ (์†Œ๋ฌธ์ž)
print(f"{42:x}")  # 2a

# 16์ง„์ˆ˜ (๋Œ€๋ฌธ์ž)
print(f"{42:X}")  # 2A

# ์ง€์ˆ˜ ํ‘œ๊ธฐ๋ฒ•
print(f"{1234567:e}")  # 1.234567e+06

# ๋ฐฑ๋ถ„์œจ
print(f"{0.25:%}")  # 25.000000%
print(f"{0.25:.0%}")  # 25%

# ์†Œ์ˆ˜์  ์ž๋ฆฟ์ˆ˜ ์ง€์ •
pi = 3.14159265359
print(f"{pi:.2f}")  # 3.14
print(f"{pi:.4f}")  # 3.1416

# ์ถœ๋ ฅ ๋„ˆ๋น„ ์ง€์ •
for i in range(1, 11):
    print(f"{i:2d} {i*i:3d} {i*i*i:4d}")

3๏ธโƒฃ ํŒŒ์ผ ์ž…์ถœ๋ ฅ

1. ํ…์ŠคํŠธ ํŒŒ์ผ ๊ธฐ๋ณธ ์ž‘์—…

# ํŒŒ์ผ ์“ฐ๊ธฐ (write mode)
with open('example.txt', 'w', encoding='utf-8') as f:
    f.write('์ฒซ ๋ฒˆ์งธ ์ค„\n')
    f.write('๋‘ ๋ฒˆ์งธ ์ค„\n')
    
    # ์—ฌ๋Ÿฌ ์ค„ ํ•œ๋ฒˆ์— ์“ฐ๊ธฐ
    lines = ['์„ธ ๋ฒˆ์งธ ์ค„\n', '๋„ค ๋ฒˆ์งธ ์ค„\n', '๋‹ค์„ฏ ๋ฒˆ์งธ ์ค„\n']
    f.writelines(lines)

# ํŒŒ์ผ ์ฝ๊ธฐ (read mode)
with open('example.txt', 'r', encoding='utf-8') as f:
    # ํŒŒ์ผ ์ „์ฒด ์ฝ๊ธฐ
    content = f.read()
    print(content)

# ํ•œ ์ค„์”ฉ ์ฝ๊ธฐ
with open('example.txt', 'r', encoding='utf-8') as f:
    first_line = f.readline()  # ํ•œ ์ค„ ์ฝ๊ธฐ
    print(first_line, end='')  # ์ด๋ฏธ \n์ด ํฌํ•จ๋˜์–ด ์žˆ์Œ
    
    # ๋ชจ๋“  ์ค„ ์ฝ๊ธฐ
    for line in f:  # ํŒŒ์ผ ๊ฐ์ฒด๋Š” ์ดํ„ฐ๋Ÿฌ๋ธ”
        print(line, end='')
        
# ๋ชจ๋“  ์ค„์„ ๋ฆฌ์ŠคํŠธ๋กœ ์ฝ๊ธฐ
with open('example.txt', 'r', encoding='utf-8') as f:
    lines = f.readlines()  # ์ค„ ๋‹จ์œ„๋กœ ๋ฆฌ์ŠคํŠธ ๋ฐ˜ํ™˜
    print(lines)  # ['์ฒซ ๋ฒˆ์งธ ์ค„\n', '๋‘ ๋ฒˆ์งธ ์ค„\n', ...]

# ํŒŒ์ผ์— ๋‚ด์šฉ ์ถ”๊ฐ€ (append mode)
with open('example.txt', 'a', encoding='utf-8') as f:
    f.write('์ถ”๊ฐ€๋œ ์ค„\n')

2. ๋‹ค์–‘ํ•œ ํŒŒ์ผ ๋ชจ๋“œ

# 'w': ์“ฐ๊ธฐ ๋ชจ๋“œ (ํŒŒ์ผ์ด ์žˆ์œผ๋ฉด ๋‚ด์šฉ ์ง€์šฐ๊ณ  ์ƒˆ๋กœ ์ž‘์„ฑ)
with open('file.txt', 'w', encoding='utf-8') as f:
    f.write('์ƒˆ๋กœ์šด ๋‚ด์šฉ\n')

# 'r': ์ฝ๊ธฐ ๋ชจ๋“œ (๊ธฐ๋ณธ๊ฐ’)
with open('file.txt', 'r', encoding='utf-8') as f:
    content = f.read()

# 'a': ์ถ”๊ฐ€ ๋ชจ๋“œ (ํŒŒ์ผ ๋์— ๋‚ด์šฉ ์ถ”๊ฐ€)
with open('file.txt', 'a', encoding='utf-8') as f:
    f.write('์ถ”๊ฐ€ ๋‚ด์šฉ\n')

# 'x': ๋ฐฐํƒ€์  ์ƒ์„ฑ ๋ชจ๋“œ (ํŒŒ์ผ์ด ์ด๋ฏธ ์žˆ์œผ๋ฉด ์‹คํŒจ)
try:
    with open('new_file.txt', 'x', encoding='utf-8') as f:
        f.write('์ƒˆ ํŒŒ์ผ ๋‚ด์šฉ\n')
except FileExistsError:
    print('ํŒŒ์ผ์ด ์ด๋ฏธ ์กด์žฌํ•ฉ๋‹ˆ๋‹ค.')

# 'b': ๋ฐ”์ด๋„ˆ๋ฆฌ ๋ชจ๋“œ (ํ…์ŠคํŠธ ๋ชจ๋“œ์™€ ํ•จ๊ป˜ ์‚ฌ์šฉ)
with open('binary.dat', 'wb') as f:  # ๋ฐ”์ด๋„ˆ๋ฆฌ ์“ฐ๊ธฐ
    f.write(b'Binary data')

with open('binary.dat', 'rb') as f:  # ๋ฐ”์ด๋„ˆ๋ฆฌ ์ฝ๊ธฐ
    binary_data = f.read()

# '+': ์ฝ๊ธฐ/์“ฐ๊ธฐ ๋ชจ๋“œ (๋‹ค๋ฅธ ๋ชจ๋“œ์™€ ํ•จ๊ป˜ ์‚ฌ์šฉ)
with open('file.txt', 'r+', encoding='utf-8') as f:  # ์ฝ๊ธฐ+์“ฐ๊ธฐ
    content = f.read()
    f.write('ํŒŒ์ผ ๋์— ์ถ”๊ฐ€\n')

with open('file.txt', 'w+', encoding='utf-8') as f:  # ์“ฐ๊ธฐ+์ฝ๊ธฐ
    f.write('์ƒˆ ๋‚ด์šฉ\n')
    f.seek(0)  # ํŒŒ์ผ ํฌ์ธํ„ฐ๋ฅผ ์ฒ˜์Œ์œผ๋กœ ์ด๋™
    content = f.read()

3. ํŒŒ์ผ ์œ„์น˜ ์ œ์–ด์™€ ์ž„์˜ ์ ‘๊ทผ

with open('example.txt', 'r+', encoding='utf-8') as f:
    # ํ˜„์žฌ ์œ„์น˜ ํ™•์ธ
    pos = f.tell()
    print(f"ํ˜„์žฌ ์œ„์น˜: {pos}")
    
    # ์œ„์น˜ ์ด๋™
    f.seek(10)  # 10๋ฒˆ์งธ ๋ฐ”์ดํŠธ๋กœ ์ด๋™
    print(f"10๋ฒˆ์งธ ์œ„์น˜์˜ ๋ฌธ์ž: {f.read(1)}")
    
    # ์ฒ˜์Œ์œผ๋กœ ์ด๋™
    f.seek(0)
    print(f"์ฒ˜์Œ์œผ๋กœ ์ด๋™ ํ›„ ์ฝ๊ธฐ: {f.read(5)}")
    
    # ์ƒ๋Œ€์  ์ด๋™
    f.seek(0)  # ๋จผ์ € ์ฒ˜์Œ์œผ๋กœ ์ด๋™
    f.read(5)  # 5๊ธ€์ž ์ฝ๊ธฐ
    f.seek(10, 1)  # ํ˜„์žฌ ์œ„์น˜์—์„œ 10๋ฐ”์ดํŠธ ์•ž์œผ๋กœ
    print(f"์ƒ๋Œ€ ์ด๋™ ํ›„ ์ฝ๊ธฐ: {f.read(5)}")
    
    # ํŒŒ์ผ ๋์œผ๋กœ ์ด๋™
    f.seek(0, 2)  # 2๋Š” ํŒŒ์ผ ๋์„ ์˜๋ฏธ
    print(f"ํŒŒ์ผ ๋ ์œ„์น˜: {f.tell()}")

4. CSV ํŒŒ์ผ ๋‹ค๋ฃจ๊ธฐ

import csv

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

with open('data.csv', 'w', newline='', encoding='utf-8') as f:
    writer = csv.writer(f)
    writer.writerows(data)  # ์—ฌ๋Ÿฌ ํ–‰ ํ•œ๋ฒˆ์— ์“ฐ๊ธฐ
    
    # ๋˜๋Š” ํ–‰๋ณ„๋กœ ์“ฐ๊ธฐ
    # for row in data:
    #     writer.writerow(row)

# CSV ํŒŒ์ผ ์ฝ๊ธฐ
with open('data.csv', 'r', encoding='utf-8') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)

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

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

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

5. JSON ํŒŒ์ผ ๋‹ค๋ฃจ๊ธฐ

import json

# JSON ํŒŒ์ผ ์“ฐ๊ธฐ
data = {
    'name': 'Kim',
    'age': 25,
    'skills': ['Python', 'JavaScript'],
    'active': True,
    'details': {
        'email': '[email protected]',
        'phone': '010-1234-5678'
    }
}

with open('data.json', 'w', encoding='utf-8') as f:
    json.dump(data, f, ensure_ascii=False, indent=2)  # ํ•œ๊ธ€ ๊ทธ๋Œ€๋กœ ์ €์žฅ, ๋“ค์—ฌ์“ฐ๊ธฐ ์ ์šฉ

# JSON ํŒŒ์ผ ์ฝ๊ธฐ
with open('data.json', 'r', encoding='utf-8') as f:
    loaded_data = json.load(f)
    print(loaded_data['name'])
    print(loaded_data['skills'][0])
    print(loaded_data['details']['email'])

# JSON ๋ฌธ์ž์—ด ๋ณ€ํ™˜
json_str = json.dumps(data, ensure_ascii=False)
print(json_str)

# JSON ๋ฌธ์ž์—ด ํŒŒ์‹ฑ
parsed_data = json.loads(json_str)
print(parsed_data['age'])

6. ๋ฐ”์ด๋„ˆ๋ฆฌ ํŒŒ์ผ ๋‹ค๋ฃจ๊ธฐ

# ๋ฐ”์ด๋„ˆ๋ฆฌ ๋ฐ์ดํ„ฐ ์“ฐ๊ธฐ
with open('binary.dat', 'wb') as f:
    # ๋ฐ”์ดํŠธ ๋ฐ์ดํ„ฐ ์“ฐ๊ธฐ
    f.write(b'Hello, binary world!')
    
    # ์ •์ˆ˜ ๊ฐ’์„ ๋ฐ”์ดํŠธ๋กœ ๋ณ€ํ™˜ํ•˜์—ฌ ์“ฐ๊ธฐ
    import struct
    numbers = [1, 2, 3, 4, 5]
    for num in numbers:
        f.write(struct.pack('i', num))  # 'i'๋Š” 4๋ฐ”์ดํŠธ ์ •์ˆ˜ ํ˜•์‹

# ๋ฐ”์ด๋„ˆ๋ฆฌ ๋ฐ์ดํ„ฐ ์ฝ๊ธฐ
with open('binary.dat', 'rb') as f:
    # ์ฒ˜์Œ 21๋ฐ”์ดํŠธ ์ฝ๊ธฐ (๋ฌธ์ž์—ด)
    text = f.read(21)
    print(text)  # b'Hello, binary world!'
    
    # 4๋ฐ”์ดํŠธ์”ฉ ์ฝ์–ด์„œ ์ •์ˆ˜๋กœ ๋ณ€ํ™˜
    import struct
    numbers = []
    while True:
        data = f.read(4)  # 4๋ฐ”์ดํŠธ ์ฝ๊ธฐ
        if not data:  # ํŒŒ์ผ ๋์ด๋ฉด ์ข…๋ฃŒ
            break
        number = struct.unpack('i', data)[0]
        numbers.append(number)
    
    print(numbers)  # [1, 2, 3, 4, 5]

7. ํŒŒ์ผ ๋ฐ ๋””๋ ‰ํ† ๋ฆฌ ๊ด€๋ฆฌ

import os
import shutil

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

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

# ํŒŒ์ผ ํฌ๊ธฐ ํ™•์ธ
if os.path.exists('example.txt'):
    size = os.path.getsize('example.txt')
    print(f'ํŒŒ์ผ ํฌ๊ธฐ: {size} ๋ฐ”์ดํŠธ')

# ํŒŒ์ผ ์ด๋ฆ„ ๋ณ€๊ฒฝ
if os.path.exists('example.txt'):
    os.rename('example.txt', 'new_name.txt')

# ํŒŒ์ผ ๋ณต์‚ฌ
if os.path.exists('new_name.txt'):
    shutil.copy('new_name.txt', 'copy.txt')

# ํŒŒ์ผ ์ด๋™
if os.path.exists('copy.txt'):
    if not os.path.exists('temp'):
        os.mkdir('temp')  # ๋””๋ ‰ํ† ๋ฆฌ ์ƒ์„ฑ
    shutil.move('copy.txt', 'temp/moved.txt')

# ํŒŒ์ผ ์‚ญ์ œ
if os.path.exists('new_name.txt'):
    os.remove('new_name.txt')

# ๋””๋ ‰ํ† ๋ฆฌ ์ƒ์„ฑ
if not os.path.exists('new_dir'):
    os.mkdir('new_dir')  # ๋‹จ์ผ ๋””๋ ‰ํ† ๋ฆฌ ์ƒ์„ฑ
    # os.makedirs('path/to/nested/dir')  # ์ค‘์ฒฉ ๋””๋ ‰ํ† ๋ฆฌ ์ƒ์„ฑ

# ๋””๋ ‰ํ† ๋ฆฌ ์‚ญ์ œ
if os.path.exists('new_dir'):
    os.rmdir('new_dir')  # ๋นˆ ๋””๋ ‰ํ† ๋ฆฌ๋งŒ ์‚ญ์ œ ๊ฐ€๋Šฅ
    # shutil.rmtree('dir_with_files')  # ํŒŒ์ผ์ด ์žˆ๋Š” ๋””๋ ‰ํ† ๋ฆฌ ์‚ญ์ œ

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

# ๋””๋ ‰ํ† ๋ฆฌ ๋‚ด์šฉ ๋‚˜์—ด
if os.path.exists('.'):
    files = os.listdir('.')
    print('ํ˜„์žฌ ๋””๋ ‰ํ† ๋ฆฌ ๋‚ด์šฉ:')
    for file in files:
        print(f'- {file}')

4๏ธโƒฃ ํ‘œ์ค€ ์ž…์ถœ๋ ฅ ์ŠคํŠธ๋ฆผ

ํŒŒ์ด์ฌ์—์„œ๋Š” ์„ธ ๊ฐ€์ง€ ๊ธฐ๋ณธ ์ŠคํŠธ๋ฆผ์„ ์ œ๊ณตํ•œ๋‹ค.

import sys

# ํ‘œ์ค€ ์ถœ๋ ฅ (Standard Output)
sys.stdout.write("ํ‘œ์ค€ ์ถœ๋ ฅ์— ์ง์ ‘ ์“ฐ๊ธฐ\n")
print("print ํ•จ์ˆ˜๋Š” sys.stdout์— ์ถœ๋ ฅํ•ฉ๋‹ˆ๋‹ค.")

# ํ‘œ์ค€ ์˜ค๋ฅ˜ (Standard Error)
sys.stderr.write("์˜ค๋ฅ˜ ๋ฉ”์‹œ์ง€๋ฅผ ์ถœ๋ ฅํ•ฉ๋‹ˆ๋‹ค.\n")

# ํ‘œ์ค€ ์ž…๋ ฅ (Standard Input)
print("์ด๋ฆ„์„ ์ž…๋ ฅํ•˜์„ธ์š”:")
name = sys.stdin.readline().strip()  # input() ํ•จ์ˆ˜์˜ ๊ธฐ๋ณธ ๋™์ž‘
print(f"์ž…๋ ฅํ•œ ์ด๋ฆ„: {name}")

# ์ถœ๋ ฅ ๋ฆฌ๋‹ค์ด๋ ‰์…˜ ์˜ˆ์ œ
original_stdout = sys.stdout  # ์›๋ž˜ stdout ์ €์žฅ

# ํŒŒ์ผ๋กœ ์ถœ๋ ฅ ๋ฆฌ๋‹ค์ด๋ ‰์…˜
with open('output.txt', 'w', encoding='utf-8') as f:
    sys.stdout = f  # stdout์„ ํŒŒ์ผ๋กœ ๋ณ€๊ฒฝ
    print("์ด ๋‚ด์šฉ์€ ํŒŒ์ผ์— ๊ธฐ๋ก๋ฉ๋‹ˆ๋‹ค.")
    print("์ด ๋‚ด์šฉ๋„ ํŒŒ์ผ์— ๊ธฐ๋ก๋ฉ๋‹ˆ๋‹ค.")

sys.stdout = original_stdout  # stdout ๋ณต์›
print("๋‹ค์‹œ ์ฝ˜์†”์— ์ถœ๋ ฅ๋ฉ๋‹ˆ๋‹ค.")

5๏ธโƒฃ ๊ณ ๊ธ‰ ์ž…์ถœ๋ ฅ ๊ธฐ๋ฒ•

1. ์ง๋ ฌํ™”์™€ ์—ญ์ง๋ ฌํ™” (pickle)

import pickle

# ๋ณต์žกํ•œ ๊ฐ์ฒด ์ƒ์„ฑ
data = {
    'name': 'Alice',
    'age': 30,
    'grades': [85, 90, 92],
    'details': {
        'address': '์„œ์šธ์‹œ ๊ฐ•๋‚จ๊ตฌ',
        'phone': '010-1234-5678'
    }
}

# ๊ฐ์ฒด ์ง๋ ฌํ™” (์ €์žฅ)
with open('data.pkl', 'wb') as f:
    pickle.dump(data, f)

# ๊ฐ์ฒด ์—ญ์ง๋ ฌํ™” (๋กœ๋“œ)
with open('data.pkl', 'rb') as f:
    loaded_data = pickle.load(f)

print(loaded_data)
print(f"์ด๋ฆ„: {loaded_data['name']}")
print(f"์ƒ์„ธ ์ •๋ณด: {loaded_data['details']}")

# ์—ฌ๋Ÿฌ ๊ฐ์ฒด ์ง๋ ฌํ™”
objects = [
    [1, 2, 3, 4],
    {'a': 1, 'b': 2},
    'Hello, Pickle',
    (5, 6, 7)
]

with open('multiple.pkl', 'wb') as f:
    for obj in objects:
        pickle.dump(obj, f)

# ์—ฌ๋Ÿฌ ๊ฐ์ฒด ์—ญ์ง๋ ฌํ™”
with open('multiple.pkl', 'rb') as f:
    try:
        while True:
            obj = pickle.load(f)
            print(obj)
    except EOFError:
        # ํŒŒ์ผ ๋์— ๋„๋‹ฌํ•˜๋ฉด EOFError ๋ฐœ์ƒ
        pass

2. ๋ฉ”๋ชจ๋ฆฌ ๋‚ด ํŒŒ์ผ ๊ฐ์ฒด (StringIO, BytesIO)

from io import StringIO, BytesIO

# ๋ฌธ์ž์—ด ๊ธฐ๋ฐ˜ ํŒŒ์ผ ๊ฐ์ฒด
output = StringIO()
output.write('First line.\n')
output.write('Second line.\n')

# ํ˜„์žฌ ๊ฐ’ ์–ป๊ธฐ
contents = output.getvalue()
print(contents)

# ์ฒ˜์Œ์œผ๋กœ ์œ„์น˜ ์ด๋™
output.seek(0)

# ์ฝ๊ธฐ
print(output.read())

# ๋‹ซ๊ธฐ
output.close()

# ์ดˆ๊ธฐ ๋‚ด์šฉ์œผ๋กœ ์ƒ์„ฑ
input = StringIO('Initial value.\nAnother line.\n')
print(input.read())
input.close()

# ๋ฐ”์ด๋„ˆ๋ฆฌ ๋ฐ์ดํ„ฐ์šฉ BytesIO
binary_output = BytesIO()
binary_output.write(b'Binary data\n')
binary_output.write(b'More binary data\n')

# ์ฒ˜์Œ์œผ๋กœ ์ด๋™
binary_output.seek(0)
print(binary_output.read())
binary_output.close()

์ฃผ์š” ํŒ

โœ… ์ž…์ถœ๋ ฅ ๋ชจ๋ฒ” ์‚ฌ๋ก€:

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


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