본문 바로가기
Study/파이썬

파이썬 readline, readlines, read

by ChatBotBunny 2019. 12. 29.

1. readline  함수 

파일의 첫번째 줄을 읽어들이는 함수 

 

= open(r"D:\05.Study\Python\myRepository\NewFile.txt",'r')
line = f.readline() #  read the first line of file 
#print(line)
 
 
# read all line 
while True:
    line = f.readline()
    if not line: break 
    print(line)
    
f.close()
 

 

2. readlines 함수 

파일의 모든줄을 한꺼번에 읽어서 리스트에 저장 

= open(r"D:\05.Study\Python\myRepository\NewFile.txt",'r')
lines = f.readlines()
 
for line in lines: 
    print(line)
    
f.close()
 

리스트에 저장된다. 

 

3. read 함수 

파일의 내용을 한꺼번에 읽어서 전체를 문자열로 저장한다. 

= open(r"D:\05.Study\Python\myRepository\NewFile.txt",'r')
lines = f.read()
   
f.close()
 

문자열로 저장해버린다.