여러줄 읽기 readlines( )
파일의 모든 데이터를 읽어서 리스트 형태로 반환한다.
open한 객체를 담은 변수명.readlines( )
lans.txt |
hello python hello c++ hello java hello javascript |
url = '경로/~/'
with opne(url+'lans.txt', 'r') as f:
lanList = f.readlines()
print(f'lanList: {lanList}')
print(f'lanList type: {type(lanList)}')
-- 출력 -- |
lanList: ['hello python\n', 'hello c++ \n ', 'hello java\n ', 'hello javascript\n '] lanList type: <class 'list'> |
한줄 읽기 readline( )
한 행씩 읽엇 문자열로 반환 한다.
open한 객체를 담은 변수명.readline( )
lans.txt |
hello python hello c++ hello java hello javascript |
url = '경로/~/'
with opne(url+'lans.txt', 'r') as f:
line = f.readline()
while line != '': #읽어들인 줄이 비어있지 않다면 반복(맨끝줄이 아니라면)
print(f'line: {line}') #읽어들일 줄에 개행이 있어서 한줄의 여백이 생김. 한줄 여백을 없애려면 end='' 옵션을 사용
line = f.readline()
-- 출력 -- |
line: hello python
line: hello c++
line: hello java
line: hello javascript |
[실습]
파일에 저장된 과목별 점수를 파이썬에서 읽어, 딕셔너리에 저장하는 코드를 만들어보자.
scores.txt |
kor:85 eng:90 math:92 sci:79 his:82 |
scoreDict = {}
uri = '경로/~/'
with open(uri+'scores.txt', 'r') as f:
line f.readline()
while line != '':
tempList = line.split(':')
scoreDict[tempList[0]] = int(tempList[1].strip('\n'))
line = f.readline()
print(f'scoreDict: {scoreDict}')
-- 출력 -- |
scoreDict: {'kor': 85, 'eng': 90, 'math': 92, 'sci': 79, 'his': 82} |