[Python 기초]

[Python] 파일 처리 및 외부 리소스 정리

dyk98 2024. 11. 27. 19:27

1. 파일 열기와 닫기

파일 열기

  • open() 함수를 사용해 파일을 엽니다.
  • 파일 모드:
    • "r": 읽기 모드 (기본값). 파일이 없으면 오류 발생.
    • "w": 쓰기 모드. 파일이 없으면 새로 생성, 기존 내용은 덮어씌움.
    • "a": 추가 모드. 기존 내용 뒤에 데이터 추가.
    • "b": 바이너리 모드. 이진 파일 처리.

파일 닫기

  • close() 메서드를 사용해 파일을 닫아야 합니다.
  • 파일을 닫지 않으면 데이터 손실이나 잠금 문제가 발생할 수 있습니다.

with 문

  • 파일을 열고 닫는 과정을 자동으로 처리.
with open("example.txt", "r") as file:
    content = file.read()

2. 파일 읽기

read()

  • 파일 전체 내용을 읽음.
with open("example.txt", "r") as file:
    content = file.read()

readline()

  • 파일의 한 줄을 읽음.
with open("example.txt", "r") as file:
    line = file.readline()

readlines()

  • 파일의 모든 줄을 읽고, 각 줄을 리스트로 반환.
with open("example.txt", "r") as file:
    lines = file.readlines()
    for line in lines:
        print(line.strip())

 

3. 파일 쓰기

write()

  • 문자열 데이터를 파일에 씀. 기존 내용을 덮어씀.
with open("output.txt", "w") as file:
    file.write("새로운 내용")

writelines()

  • 문자열 리스트를 한꺼번에 파일에 씀.
lines = ["첫 번째 줄\\n", "두 번째 줄\\n"]
with open("output.txt", "w") as file:
    file.writelines(lines)

추가 모드 ("a")

  • 기존 내용 뒤에 데이터를 추가.
with open("output.txt", "a") as file:
    file.write("추가 내용")

4. 파일 처리 시 주의사항

1) 파일 경로

  • 파일 경로를 올바르게 지정 (상대 경로/절대 경로).

2) 파일 모드

  • 작업에 맞는 파일 모드 선택. (읽기/쓰기/추가)

3) 파일 닫기

  • 반드시 파일을 닫아야 하며, with 문을 사용하면 안전.

4) 예외 처리

  • 파일이 없거나 권한 문제가 발생할 경우를 대비.
try:
    with open("example.txt", "r") as file:
        content = file.read()
except FileNotFoundError:
    print("파일을 찾을 수 없습니다.")
except IOError:
    print("파일 처리 중 오류가 발생했습니다.")

5. 파일 처리 정리….

  1. 파일 열기: open("파일이름", "모드")
  2. 파일 읽기: read(), readline(), readlines()
  3. 파일 쓰기: write(), writelines()
  4. 파일 닫기: close() 또는 with 문 사용
  5. 예외 처리: try-except 블록 사용