-
[Python] 2-2 파일 읽기05. Programing Language/[Python] 1. 파이썬 자료구조 2020. 1. 13. 16:06
티타임 1. 시퀀스로써 파일 핸들
xfile = open('mbox.txt') for cheese in xfile: print(cheese)
-읽기용으로 열린 파일 핸들은
파일의 각 줄에 대한 문자열의 시퀀스(순서)로 볼 수 있다.
-for문을 사용하여 시퀀스를 반복하여 돌 수 있다.
-시퀀스는 정렬된 집합임을 기억하기
-쉽게 말해 cheese가 파일의 한줄씩 받아와서 출력해준다고 보면 되겠다.
2. 파일 *전체*를 읽기
fhand = open('mbox-short.txt') inp = fhand.read() print(len(inp)) #94626 print(inp[:20]) #From stephen.marquar
-파일 전체(개행 문자 포함 전체)를 하나의 문자열로 읽는 것
-10만 줄은 괜찮지만 그이상 1000만줄을 하나의 문자열로
읽으면 그리 좋지 않을 것이다.
3. 파일 내용 탐색
fhand = open('mbox-short.txt') for line in fhand: if line.startswith('Frome:'): print(line)
-접두사 Frome: 으로 시작하는 줄 만 출력하는 것.
-출력을 해보면 줄마다 빈 줄이 추가된다 그 이유는
print() 함수 자체적으로 줄바꿈 기능이 추가 되어있기 때문이다.
즉 줄마다 있는 개행문자 + print()함수의 줄바꿈 기능이 합쳐져
빈 줄이 추가 되는 것이다.
3-1 파일 내용 탐색 (전형적인 방법)
fhand = open('mbox-short.txt') for line in fhand: line = line.rstrip() if line.startswith('From:') : print(line)
-rstrip() 을 활용하여 오른쪽에서부터 공백을 지울 수 있다.
-개행 문자는 '공백'으로 취급되어 제거된다!
3-2 줄을 선택하기위해 in 사용 하기
fhand = open('mbox-short.txt') for line in fhand: line = line.rstrip() if not '@uct.ac.za' in line: continue print(line)
4. 파일명에 대한 프롬프트
fname = input('Enter the file name: ') fhand = open(fname) count = 0 for line in fhand: if line.startswith('Subject: ') : count = count + 1 print('There were', count, 'subject lines in', fname)
- 어떤작업인지 굳이 설명 하지 않겠습니다.
5. 부적절한 파일명
fname = input('Enter the file name: ') try: fhand = open(fname) except: print('File cannot be opened:', fname) quit() count = 0 for line in fhand: if line.startswith('Subject: ') : count = count + 1 print('There were', count, 'subject lines in', fname)
-에러처리 해주었구요
끝!
'05. Programing Language > [Python] 1. 파이썬 자료구조' 카테고리의 다른 글
[Python] 3-1 리스트의 개념 및 특징 (0) 2020.01.14 [Python] 2-3 <실습> 파일 열고 읽기 (0) 2020.01.13 [Python] 2-1 파일 열기 (0) 2020.01.13 [Python] 1-3 <실습> 문자열 파싱 (0) 2020.01.09 [Python] 1-2 문자열을 다루는 다양한 방법들 (0) 2020.01.08