파일 오픈 함수: open()

파일 입출력을 위한 모드

  • 읽기모드(r): 파일을 읽기 전용으로 열기. 파일이 존재하지 않을 시 오류 발생
  • 쓰기모드(w): 파일을 쓰기 전용으로 열기. 파일이 존재할 경우 기존 파일에 덮어 쓰기
  • 추가모드(a): 파일을 쓰는것은 똑같지만 이미 파일이 존재할 경우 기존 파일에 덮는것이 아닌 데이터 끝에 추가를 하게됨

두가지 방법

  • open()
  • with open()

 

read(), open() 파일 입출력


open()

  • open("파일명", "옵션") 함수를 통해서 파일을 읽고 쓸 수 있다.
  • 한글 깨짐 방지: utf-8을 이용하려면 encoding 옵션을 주어야 한다.
  • open()을 진행한 뒤 반드시 close()를 진행해야 한다. 안해줄 시 계속 메모리에 남아있게 된다.
helloFile = open('hello.txt', 'w', encoding="utf-8")
helloFile.write("Hello, world!\n")

helloFile.close()

 

read()

  • read() 메소드를 통해서 파일을 읽고 하나의 문자열로 반환
helloFile = open('hello.txt', 'r', encoding="utf-8")
content = helloFile.read()
print(content)
helloFile.close()
hello.txt

Hello, World!

 

with read(), with open() 파일 입출력


with open()

  • with 문은 파일을 열고 작업한 후 자동으로 파일을 닫는 기능을 제공
  • close() 명령어가 따로 필요 없음
  • with 사용 시 코드가 간결해지고, 예외 발생 시에도 닫히도록 보장
  • open()보다 요즘은 with를 사용
with open('example.txt','w',encoding='utf-8') as file:
    file.write("line1: Hello, World!\n")
    file.write("line2: This is second line\n")

with open()

  • read() : 파일 전체를 문자열 형태로 읽는다.
  • readline() : 파일에서 한문장만 읽는다.
  • readlines(): 파일을 문장단위로 리스트에 삽입한다. 리스트형태로 출력된다.
with open('example.txt','r',encoding='utf-8') as file:
    content = file.read()
    print(content)
example.txt

line1: Hello, World!
line2: This is second line

 

+ Recent posts