인공지능/파이썬

파이썬(Python) - 파일 열기 모드 / with문

해피밀세트 2020. 2. 26. 19:46
반응형

 

 

파일 열기 모드

파일 열기 모드 설명
w 쓰기모드 - 파일에 내용을 쓸 때 사용
a 추가모드 - 파일의 마지막에 새로운 내용을 추가 시킬 때 사용
r 읽기모드 - 파일을 읽기만 할 때 사용

 

1. w - 쓰기모드

 

쓰기모드를 사용하면 지정한 경로에 파일을 생성하고 내용을 작성 할 수 있다. :

file = open("C:/python_test/test.txt","w")
for i in range(10,51,10):
    a = "기분이 {}만큼 좋아!\n".format(i)
    file.write(a)
file.close()

 

만약 기존파일이 있다면 덮어쓰게된다.(주의하자!!) :

file = open("C:/python_test/test.txt","w")
for i in range(50,101,10):
    a = "기분이 {}만큼 좋아!\n".format(i)
    file.write(a)
file.close()

 

 

2. a - 추가모드

 

추가모드를 사용하면 기존의 내용에 입력한 내용이 추가된다. :

file = open("C:/python_test/test.txt","a")
for i in range(10,51,10):
    a = "기분이 {}만큼 좋아!\n".format(i)
    file.write(a)
file.close()

 

 

3. r - 읽기모드

 

1) 한줄씩 읽어들이기 :

file = open("C:/python_test/test.txt","r")
while True :
    data = file.readline()      # 한줄씩 읽어 들이는 함수
    if not data:                  # 읽어들일 내용이 없으면 반복 중단
        break
    else :
        print(data, end="")    # end=""를 사용해서 줄사이를 붙인다.
file.close()

 

없는 파일을 읽어 들이려고 하면 오류가 난다.

file = open("C:/python_test/miss.txt","r")

때문에 읽기모드를 사용하기 전에  파일 존재 여부를 확인하자 :

import os
os.path.exists("C:/python_test/miss.txt")

 

2) 파일 내용 전체를 리스트로 출력

file = open("C:/python_test/test.txt","r")
data = file.readlines() 
print(data)
file.close()

 

3) 파일의 내용 전체를 문자열로 출력

file = open("C:/python_test/test.txt","r")
data = file.read() 
print(data)
file.close()

 

 

!! 주의 사항 !!

 

동일한 파일로 reader하면 한 개의 파일을 같이 쓰는것이다.

file = open("C:/data/emp_200310.csv","r")

emp_csv = csv.reader(file)

next(emp_csv)

emp_csv = csv.reader(file)

next(emp_csv)

 

 


 

with문

  • 파일객체를 자동으로 닫아주는

 

파일을 불러온뒤 close()를 쓰지 않아도 자동으로 닫힌다. :

from datetime import datetime
with open("C:/python_test/birthday.txt","w") as file :
    for i in range(1, 6):
        a = "생일까지 앞으로 D-{} \n".format(int((datetime(2020,7,13) - datetime(2020,2,26)).days)-i)
        file.write(a)

 

리스트로도 넣을 수 있다. :

txt = ["안녕하세요.","블로그 많이 들어와 주세요."]
with open("C:/python_test/birthday.txt","w") as file :
    for i in txt :
        file.write(i + "\n")

 

with문 + 읽기 모드 :

with open("C:/python_test/hello.txt","r") as file :
    data = file.readlines()
    for i in data :
        print(i, end="")

 

하나의 문장으로 출력 (리스트 형식 / 권장하지 않음) :
with open("C:/python_test/hello.txt","r") as file :  
    print(file.readlines(), end="") 

 

하나의 문장으로 출력 (print할때 \n 때문에 다음줄로 넘어간다.) :
with open("C:/data/test_new.txt","r") as file :  
    print(file.read(), end="") 

반응형