[Python] 6. 파일 입출력

1. 파일 입출력

파이썬에 파일 입출력은 open() 함수를 사용해 파일을 열고, 읽기 또는 쓰기 작업을 수행한 후 close() 메서드로 파일을 닫습니다. 파일 입출력의 기본적인 예제는 아래와 같습니다.

  • 파일 쓰기
# 파일 열기 (쓰기 모드)
with open('example.txt', 'w') as file:
      file.write("Hello, Python File Write")
      file.write("Finish Python File Write")
  • 파일 읽기
# 파일 읽기 (읽기 모드)
with open('example.txt', 'r') as file:
    contents = file.read()
    print(contents)
  • 파일 한 줄씩 읽기

redline() 메서드를 사용해 파일을 한 줄씩 읽을 수 있습니다.

with open('example.txt', 'r') as file:
     line = file.readline() # 첫 번째 줄 읽기
     while line:
         print(line, end= '') # 줄바꿈 없이 출력
         line = file.readline() # 다음 줄 읽기

 


2. 추가 모드 

  • 'a' : 추가 모드 (파일 끝에 내용 추가)
  • 'r' : 읽기 모드 (기본 값)
  • 'w' : 쓰기 모드 (파일이 존재하면 덮어씀)
  • 'x' : 배타적 생성 모드 (파일이 존재하면 에러 발생)
# 파일 열기 (추가 모드)
with open('example.txt', 'a') as file:
     file.write("\n 추가: Python is Write")
     
 / ** 
 Hello, Python File WriteFinish Python File Write
 �߰�: Python is Write
 **/

3. CSV 파일 읽기 및 쓰기 

CSV 파일을 다루는 간단한 예제입니다. csv 모듈을 사용합니다.

import csv

# csv파일을 쓰기모드 'w'로 열기(인코딩 'cp949', 라인 종료 문자 설정 'newline = '')
with open('datas.csv', 'w', encoding='utf-8', newline='') as csvfile:
    writer = csv.writer(csvfile) # 파일 객체를 csv.writer의 인자로 전달해 새로운 writer 객체를 생성

    writer.writerow(['이름', '나이'])
    writer.writerow(['홍길동', 30])
    writer.writerow(['김철수', 25])
    writer.writerow(['이영희', 22])

    print("CSV 파일 작성 완료.")
import csv

# CSV 파일 읽기
with open('datas.csv', 'r', encoding="utf-8-sig") as csvfile:
    reader = csv.reader(csvfile)
    for row in reader:
          print(row)

 

GitHub - Koras02/python-blog

Contribute to Koras02/python-blog development by creating an account on GitHub.

github.com

 

LIST

'Back-End > Python' 카테고리의 다른 글

[Python] 8. 예외 처리  (0) 2025.03.02
[Python] 7. 객체지향 프로그래밍  (0) 2025.02.28
[Python] 5. 모듈과 패키지  (0) 2025.02.24
[Python] 4.함수(Function)  (0) 2025.02.22
[Python] 3. Python의 자료구조  (0) 2025.02.16