2026년 4월 26일
Language / Python[Python] 6. 파일
『데이터를 다루며 배우는 파이썬』을 참고하였고, 학교에서 수업을 들으며 필기한 내용으로 보충하였다.
목차
[1] 파일 열기
[2] 파일 읽기
[3] 파일에서 찾기
[4] 파일 이름 입력 받기
[5] 파일 쓰기
[1] 파일 열기
컴퓨터의 전원이 꺼지면 CPU와 메모리의 내용도 모두 사라진다. 이번 장에서는 보조 메모리(또는 파일) 사용법을 배운다. 보조 메모리는 전원이 꺼져도 저장된 내용이 지워지지 않으며, USB에 정보를 저장했다면 다른 시스템에 연결해 사용할 수도 있다.
하드 드라이브에 있는 파일을 읽고 쓰기 위해서는 먼저 파일을 열어야 한다. 파일을 열기 위해서는 파일이 어디에 저장됐는지 위치를 알고 있는 운영체제와 커뮤니케이션이 필요하다. 파일을 열 때는 운영체제에 파일 이름을 전달해서 해당 파일이 존재하는지 확인해야 한다. 이번 예제에서는 mbox.txt 텍스트 파일을 사용하는데, https://www.py4e.com/code3/mbox.txt 에서 내려받은 후, 파이썬이 설치된 위치에 복사해 두자.
>>> fhand = open('mbox.txt')
>>> print(fhand)<_io.TextIOWrapper name='mbox.txt' mode='r' encoding='cp949'>
open이 성공하면 운영체제는 파일 핸들(file handle) 을 반환한다. 파일 핸들은 파일의 실제 데이터가 아니지만, 핸들을 써서 데이터를 읽을 수 있다. 만약, 요청한 파일이 존재하고 파일을 읽을 수 있는 적절한 권한도 갖고 있다면 파일 핸들을 얻는다. 요청한 파일이 없다면 open은 오류 메시지와 함께 실패하며 핸들도 얻을 수 없다.
[2] 파일 읽기
>>> f = open('mbox.txt')
>>> count = 0
>>> for line in f:
count = count + 1
>>> print('Line Count:', count)Line Count: 132045
파일 핸들 f는 mbox.txt 파일에 대한 핸들이다. for문은 파일 핸들이 가리키는 파일의 각 행마다(읽어서 행 단위로 → 읽어서 '\n'을 만날 때마다) count 변수를 하나 증가시킨다. 이때 카운트를 하는 라인(count=count+1)을 두는 대신, 출력문을 두면 라인 단위로 화면에 출력될 수 있다.
f = open('mbox.txt')
count = 0
for line in f:
count = count + 1
print(line)
print(count)위의 for 루프는 한 번에 한 줄의 데이터만 읽으므로 메모리 공간을 많이 사용하지 않는다. 따라서 매우 큰 사이즈의 텍스트 파일이라도 효과적으로 읽어서 처리할 수 있다.
읽으려는 파일의 크기가 작은 경우에는 파일 핸들에 속해있는 read() 함수를 이용하여 전체 파일 내용을 문자열 변수에 저장하여 처리할 수 있다.
크기가 작은 파일을 하나 구해보자. https://www.py4e.com/code3/words.txt
f = open('words.txt')
inp = f.read()
print(inp)
print(len(inp))
print(inp[:17])Writing programs or programming is a very creative
and rewarding activity You can write programs for
many reasons ranging from making your living to solving
a difficult data analysis problem to having fun to helping
someone else solve a problem This book assumes that
{\em everyone} needs to know how to program and that once
you know how to program, you will figure out what you want
to do with your newfound skills
We are surrounded in our daily lives with computers ranging
from laptops to cell phones We can think of these computers
as our personal assistants who can take care of many things
on our behalf The hardware in our current-day computers
is essentially built to continuously ask us the question
What would you like me to do next
Our computers are fast and have vasts amounts of memory and
could be very helpful to us if we only knew the language to
speak to explain to the computer what we would like it to
do next If we knew this language we could tell the
computer to do tasks on our behalf that were reptitive
Interestingly, the kinds of things computers can do best
are often the kinds of things that we humans find boring
and mind-numbing
1171
Writing programs
read() 함수를 이용할 경우에는 함수 호출 시마다 리소스가 소비되므로 호출 결과를 변수로 저장할 필요가 있다.
f = open('words.txt')
inp = f.read()
print(len(inp))
inp = f.read()
print(len(inp))1171
0
[3] 파일에서 찾기
- 파일에서 'From:'으로 시작되는 줄만 출력해라.
- 처음부터 5개만 출력해라.
- 줄바꿈을 제거해서 출력해라.
- '@uct.ac.za' 문자열을 포함하는 줄을 찾아라.
먼저 1번은 startswith()의 문자열 메소드를 이용한다. 2번은 카운터를 두고 5보다 크면 루프를 빠져나온다.(break문)
f = open('mbox.txt')
count = 0
for line in f:
if line.startswith('From:'):
print(line)
count = count + 1
if count > 4:
breakFrom: stephen.marquard@uct.ac.za
From: louis@media.berkeley.edu
From: zqian@umich.edu
From: rjlowe@iupui.edu
From: zqian@umich.edu
3번에서 줄바꿈을 제거하라고 한다. 줄바꿈의 이유는 print() 자체가 출력하고 다음 줄로 넘기는 함수인데, 하나의 행 끝에는 \n이 있어 이 때문에 \n과 print()의 줄바꿈으로 2줄이 넘어간다. 그렇다면 하나의 행에서 끝에 붙어 있는 \n을 제거하면 된다. 이의 간단한 방법은 rstrip() 메소드를 사용하는 것이다. 이를 이용하면 오른쪽의 문자열 공백을 제거해준다.
f = open('mbox.txt')
count = 0
for line in f:
if line.startswith('From:'):
line = line.rstrip()
print(line)
count = count + 1
if count > 4:
breakFrom: stephen.marquard@uct.ac.za
From: louis@media.berkeley.edu
From: zqian@umich.edu
From: rjlowe@iupui.edu
From: zqian@umich.edu
4번의 '@uct.ac.za' 문자열은 find() 메소드를 이용해서 찾는다. find() 메소드는 문자열이 발견된 곳을 찾아 위치를 반환하거나, 발견되지 않으면 -1을 반환한다.
f = open('mbox.txt')
count = 0
for line in f:
line = line.rstrip()
if line.find('@uct.ac.za') == -1:
continue
print(line)
count = count + 1
if count > 4:
breakFrom stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
X-Authentication-Warning: nakamura.uits.iupui.edu: apache set sender to stephen.marquard@uct.ac.za using -f
From: stephen.marquard@uct.ac.za
Author: stephen.marquard@uct.ac.za
From david.horwitz@uct.ac.za Fri Jan 4 07:02:32 2008
[4] 파일 이름 입력 받기
- 'Author:'로 시작되는 5개의 라인 출력
f = open('mbox.txt')
count = 0
for line in f :
line = line.rstrip()
if line.startswith('Author:'):
count = count + 1
if count > 5:
break
print(line)Author: stephen.marquard@uct.ac.za
Author: louis@media.berkeley.edu
Author: zqian@umich.edu
Author: rjlowe@iupui.edu
Author: zqian@umich.edu
- 사용자로부터 파일 이름 입력 받기
fname = input('Enter the file name: ')
f = open(fname)
count = 0
for line in f :
line = line.rstrip()
if line.startswith('Author:'):
count = count +1
if count > 5:
break
print(line)Enter the file name: mbox.txt
Author: stephen.marquard@uct.ac.za
Author: louis@media.berkeley.edu
Author: zqian@umich.edu
Author: rjlowe@iupui.edu
Author: zqian@umich.edu
[5] 파일 쓰기
파일을 쓰기 위해서는, open() 메소드에 'w' 매개변수를 주어 쓰기용으로 open 후, 이의 핸들을 얻어서 쓸 준비를 한다.
f = open('test.txt', 'w')
line = 'Welcome'
f.write(line)
f.close()실행 결과 확인
f = open('test.txt')
line = f.read()
print(line)Welcome댓글
댓글을 불러오는 중...