과제 내용 : Chatper 7 Quiz 7 풀고 인증 글 남기기
모두를 위한 파이썬(PY4E) 7장 (파일)의 주요 내용은 다음과 같습니다.
1. 파일 열기 및 처리:
- open() 함수로 파일 열기.
- 읽기 모드 (r), 쓰기 모드(w)
fhand = open('mbox.txt', 'r')
# fhand : 파일에 대한 작업을 수행하기 위해 사용하는 변수
2. 개행 문자:
- 파일 내 각 줄의 끝에 위치.
- "\n"으로 표현됨.
※ 주요 탈출 문자(Escape Character)
3. 파이썬에서 파일 읽기:
- 파일 핸들(fhand) : 파일의 각 줄에 대한 문자열의 시퀀스
- for 문으로 파일 내 각 줄의 문자열을 반복해서 추출
xfile = open('mbox.txt')
for cheese in xfile :
print(cheese)
4. 파일의 줄 세기:
- 파일 읽기 모드로 열고 각 줄을 세기.
- for 문과 카운터 변수 사용.
fhand = open('mbox.txt')
count = 0
for line in fhand :
count += 1
print('Line Count: ', count)
5. 파일 전체 읽기:
- read() 함수로 파일 전체(개행 문자 포함)를 하나의 문자열로 읽기.
fhand = open('mbox.txt')
inp = fhand.read() # 파일 전체를 하나의 문자열로.
print(len(inp))
6. 파일 내용 탐색:
- `startswith`, `rstrip` 함수 등을 활용한 문자열 처리.
- for 문에 if문을 넣으면 특정 조건의 줄만 필터링 가능.
fhad = open('mbox-short.txt')
for line in fhand :
line = line.rstrip() # 오른쪽에 있는 공백 제거(개행 문자 공백 취급)
if line.startswith('From:') :
print(line)
7. 파일명 입력 및 오류 처리:
- 사용자 입력(input 함수)을 통해 파일명 받기.
- 잘못된 파일명에 대한 예외 처리 : try/except 구문
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)
Quiz 결과
#9기문과생도AI