티스토리 뷰
1. 파일 처리란?
- 프로그램이 외부 텍스트 파일(.txt 등)을 읽거나 쓰는 작업을 말한다.
- 파이썬에서는 open() 함수를 사용해 파일을 열고, read(), write(), close() 등을 통해 다룰 수 있다.
이번에는 파일을 통한 입출력 방법에 대해 알아보자.
파일 데이터 읽기
- 파일을 연다. open('경로/파일명','모드')
- 파일에서 데이터를 읽거나 쓸 수 있다. (모드 ='w,r,a')
- 파일과 관련된 작업이 모두 종료되면 파일을 닫는다.f.close()
1.파일 생성하기
# newfile.py
f = open("새파일.txt", 'w')
f.close()
파일_객체 = open(파일_이름, 파일_열기_모드)
파일 열기 모드
모드 | 설명 |
'r' | 읽기 모드 (파일이 없으면 오류 발생) |
'w' | 쓰기 모드 (파일이 있으면 덮어씀, 없으면 새로 생성) |
'a' | 추가 모드 (파일 끝에 내용 추가) |
'x' | 배타적 생성 (파일이 있으면 오류 발생) |
'b' | 바이너리 모드 (텍스트 아닌 파일: 이미지 등) |
't' | 텍스트 모드 (기본값) |
f = open('new.txt', 'w') #colab에서 디렉토리에서 content/생성
f.close()
- 파일을 쓰기 모드로 열면 해당 파일이 이미 존재할 경우 원래 있던 내용이 모두 사라지고 해당 파일이 존재하지 않으면 새로운 파일이 생성된다.
특정 디렉토리 생성
f = open('./sample_data/new.txt','w')
f.close()
2.파일을 쓰기 모드로 열어 내용 쓰기
- 위 예에서는 파일을 쓰기 모드로 열기만 했을 뿐, 정작 아무것도 쓰지는 않았다. 이번에는 문자열 데이터를 파일에 직접 써 보자.
f = open('new.txt', 'w')
for i in range(1,11):
data = '%d번째 줄입니다.\n' %i
f.write(data)
f.close()
with open('new2.txt','w') as f:
for i in range(1,11):
data = f'{i}번쨰줄입니다. \n'
f.write(data)
3.파일을 읽는 여러가지 방법
파이썬에는 파일을 읽는 방법이 여러 가지 있다. 이번에는 그 방법을 자세히 알아보자.
read() - 파일에 모든 줄을 읽어 드림
- f.read()는 파일의 내용 전체를 문자열로 리턴한다.
rf = open('rTest.txt', 'w')
rf.write('김길동 01012345678 \n')
rf.write('고길동 01012345678 \n')
rf.write('홍길동 01012345678 \n')
rf.close()
rf = open('rTest.txt','r')
data = rf.read()
print(data)
rf.close()
readlines() : 파일에 모든 줄 한 줄로 읽어드림
rf = open('rTest.txt','r')
data = rf.readlines()
print(data)
rf.close()
rf = open('rTest.txt','r')
lines = rf.readlines()
for line in lines:
line = line.strip() # 줄 끝의 줄 바꿈 문자를 제거한다.
print(line)
rf.close()
readline(): 파일에서 한번에 한 줄씩 읽어오기
- 새파일.txt 파일의 가장 첫 번째 줄이 화면에 출력될 것이다.
rf = open('rTest.txt','r')
data1 = rf.readline()
print(data1)
data2 = rf.readline()
print(data2)
rf.close()
만약 모든 줄을 읽어 화면에 출력하고 싶다면 다음과 같이 작성하면 된다.
- while True: 무한 루프 안에서 f.readline()을 사용해 파일을 계속 한 줄씩 읽어 들인다. 만약 더 이상 읽을 줄이 없으면 break를 수행한다(readline()은 더 이상 읽을 줄이 없을 경우, 빈 문자열('')을 리턴한다).
rf = open('rTest.txt','r')
while True:
line = rf.readline()
if not line:
break
print(line)
rf.close()
for 문으로 읽기
rf = open('rTest.txt','r')
for line in rf:
print(line)
rf.close()
4.추가 내용 작성('a'모드)
- 쓰기 모드('w')로 파일을 열 때 이미 존재하는 파일을 열면 그 파일의 내용이 모두 사라지게 된다.
- 하지만 원래 있던 값을 유지하면서 단지 새로운 값만 추가해야 할 경우도 있다. 이런 경우에는 파일을 추가 모드('a')로 열면 된다.
of = open('rTest.txt', 'a')
of.write('강감찬 01012345678 \n')
of.close()
5.CSV(comma Separated Value) 파일 사용하기
엑셀 파일을 .csv로 저장 후 사용
- sample_data 디렉토리에서 파일 생성
- sText.txt에 아래 내용을 작성하자
김길동, 41, 01012345678
고길동, 63, 01023456789
홍길동, 99, 01034567891
6. with 문을 활용한 파일 처리 (권장)
- 블록문의 형태로 생성
f = open("foo.txt", 'w')
f.write("Life is too short, you need python")
f.close()
- with문으로 변경
with open('foo2.txt','w') as f2:
f2.write('with문을 사용하여 열고 닫기')
with open("data.txt", "r", encoding="utf-8") as f:
for line in f:
print(line.strip())
- with 문을 사용하면 자동으로 close()가 호출된다.
- 코드가 더 안전하고 간결해진다.
📝 파일 처리 과제
연습 1: 파일 쓰기
사용자로부터 문자열을 입력받아 파일에 저장하는 프로그램입니다.
with open('user.txt','w') as f:
for i in range(3):
user_input = input('입력할 문장 작성:')
f.write(f'{user_input}\n')
with open('user.txt','r') as f:
data = f.read()
print(data)
'input.txt' 파일을 읽어 각 줄에 번호를 붙이고, 'numbered_output.txt'에 저장한 후 총 줄 수를 출력하는 프로그램입니다.
# 파일의 각 줄에 번호를 붙여 저장하고, 총 줄 수를 출력합니다.
line_number = 0
with open('user.txt','r') as f:
lines = f.readlines()
with open('user_out.txt','w') as out_f:
for index, line in enumerate(lines, 1):
out_f.write(f'{index} : {line}')
line_number = index
print(f'총출력줄은 {line_number}이다')
연습2:단어 수 세기
'user.txt' 파일을 읽고 파일 내의 단어 수를 세는 프로그램입니다.
w_count = 0
with open('user.txt','r') as f:
for line in f:
words = line.split()
print(words)
w_count += len(words)
print(f'총 단언수는 {w_count}입니다.')
3.연습3:
'user.txt' 파일에서 '좋은날'라는 단어를 '피곤한날'로 교체하여 'new.txt'에 저장하는 프로그램
with open('user.txt','r') as f:
content = f.read()
new_content = content.replace('좋은날','피곤한날')
with open('new_story.txt', 'w') as f:
f.write(new_content)
📝 파일 처리 과제
과제_서울의 기상정보
- csv 파일을 읽어보자
- 헤더를 제거 해 보자
- 반복문을 이용하여 데이러를 읽어보자
- 언제 가장 추웠는지 조사 해 보자
- 서울의 최저기온을 찾아보자
import csv
f = open('./sample_data/weather.csv','r')
data = csv.reader(f)
for row in data:
print(row)
f.close()
import csv
f = open('./sample_data/weather.csv','r')
data = csv.reader(f)
header = next(data)
for row in data:
print(float(row[3]), end=' ')
f.close()
import csv
f = open('./sample_data/weather.csv','r') #csv 파일을 열어서 f에 저장
data = csv.reader(f) #reader()함수를 이용하여 읽은 파일 data 할당
header = next(data) #헤더 제거,첫 번째 줄 (보통 헤더가 위치하는 곳)을 읽고 건너뜀
temp = 100 #온도 초기값, 이 값보다 낮은 값을 서로 비교해서 찾음
for row in data:
if temp > float(row[3]):
temp = float(row[3])
print(temp)
f.close()
과제 _파일에서 특정 단어 찾기
poem.txt 파일 안에 아래와 같은 내용이 있다고 가정하자
Life is short, Python is long.
Life is beautiful.
Python is powerful.
with open("poem.txt", "r", encoding="utf-8") as f:
for line in f:
if "Python" in line:
print(line.strip())
과제 _파일 복사 프로그램
source.txt 파일의 내용을 읽고, 그 내용을 copy.txt 파일에 복사하는 프로그램을 작성하시오.
with open("source.txt", "r", encoding="utf-8") as src:
content = src.read()
with open("copy.txt", "w", encoding="utf-8") as dst:
dst.write(content)
print("파일 복사가 완료되었습니다.")
728x90
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
반응형