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 = '경로/~/'withopen(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}')