Python File Handling


4. 파일 다루기(Python File Handling)

파일 입출력 기본 (open, read, write, close)

파일 입출력은 파일을 열고 데이터를 읽거나 쓰는 작업을 포함합니다. Python에서는 open 함수를 사용하여 파일을 열고, read, write 메서드를 사용하여 데이터를 읽고 씁니다. 작업이 끝나면 close 메서드로 파일을 닫아야 합니다.

# 파일 열기
file = open("example.txt", "w")

# 파일에 쓰기
file.write("Hello, World!")
file.close()

# 파일 읽기
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()

파일 경로 다루기 (os 모듈)

os 모듈은 파일 경로를 다루는 다양한 기능을 제공합니다. os.path 하위 모듈을 사용하여 경로를 조작할 수 있습니다.

import os

# 현재 작업 디렉토리 얻기
current_directory = os.getcwd()
print(current_directory)

# 디렉토리 변경
os.chdir("/path/to/new/directory")

# 파일 경로 결합
full_path = os.path.join(current_directory, "example.txt")
print(full_path)

# 파일 존재 여부 확인
exists = os.path.exists(full_path)
print(exists)

CSV 파일 다루기

CSV 파일은 콤마로 구분된 값들을 저장하는 텍스트 파일입니다. Python의 csv 모듈을 사용하여 CSV 파일을 읽고 쓸 수 있습니다.

import csv

# CSV 파일 쓰기
with open("example.csv", mode="w", newline="") as file:
    writer = csv.writer(file)
    writer.writerow(["Name", "Age", "City"])
    writer.writerow(["Alice", 30, "New York"])
    writer.writerow(["Bob", 25, "Los Angeles"])

# CSV 파일 읽기
with open("example.csv", mode="r") as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

JSON 파일 다루기

JSON 파일은 데이터를 구조화된 형태로 저장하는 파일 형식입니다. Python의 json 모듈을 사용하여 JSON 파일을 읽고 쓸 수 있습니다.

import json

data = {
    "name": "Alice",
    "age": 30,
    "city": "New York"
}

# JSON 파일 쓰기
with open("example.json", mode="w") as file:
    json.dump(data, file)

# JSON 파일 읽기
with open("example.json", mode="r") as file:
    loaded_data = json.load(file)
    print(loaded_data)

이와 같이 파일 입출력 기본, 파일 경로 다루기, CSV와 JSON 파일 다루기를 이해하면, 다양한 파일 형식을 효율적으로 처리할 수 있습니다.


Leave a Reply

Your email address will not be published. Required fields are marked *