(1) 파일 열기
(2) 파일 처리
(3) 파일 닫기
모드(Mode) : open() 함수의 마지막 매개변수
한 행씩 읽어 들이기
inFp = None # 입력파일
inStr = "" # 읽어온 문자열
inFp = open("data.txt","r",encoding="UTF-8")
inStr = inFp.readline()
print(inStr,end="")
inStr = inFp.readline()
print(inStr,end="")
inStr = inFp.readline()
print(inStr,end="")
inFp.close()
# 결과
CookBook 파이썬을 공부합니다.
완전 재밌어요
파이썬을 공부하기 잘했네요.
f = open(path, 'r', encoding = 'UTF-8')
inFp = None # 입력 파일
inStr = "" # 읽어온 문자열
inFp = open("data.txt","r",encoding="UTF-8")
while True:
inStr = inFp.readline()
if inStr == "":
break
print(inStr,end = "")
inFp.close()
# 결과
CookBook 파이썬을 공부합니다.
완전 재밌어요
파이썬을 공부하기 잘했네요.
inFp = None # 입력 파일
inStr = "" # 읽어온 문자열
inFp = open("data.txt","r",encoding="UTF-8")
inList = inFp.readlines()
print(inList)
inFp.close()
# 결과
['CookBook 파이썬을 공부합니다.\n', '완전 재밌어요\n', '파이썬을 공부하기 잘했네요.']
close()함수를 호출하지 않고 프로그램을 종료하기
with~as
문으로 파일을 열시 close()함수를 사용하지 않아도 된다.
with open("C:/Temp/data1.txt","r") as inFp:
inList = inFp.readlines()
print(inList)
파일의 내용을 한 행씩 출력
inFp = None # 입력 파일
inStr = "" # 읽어온 문자열
# fname = input("파일명을 입력하세요 : ")
# inFp = open(fname, "r", encoding="UTF-8")
inFp = open("data.txt", "r", encoding="UTF-8")
inList = inFp.readlines()
for inStr in inList:
print(inStr, end="")
inFp.close()
# 결과
CookBook 파이썬을 공부합니다.
완전 재밌어요
파이썬을 공부하기 잘했네요.
도스 명령어 type의 구현
지정한 파일의 내용을 화면에 출력
type 파일명
파일이 없을 때 오류가 발생하지 않게 하려면 os.path.exists(파일명) 형식 사용
import os
inFp = None
fName, inList, inStr = "", [], ""
fName = input("파일명을 입력하세요: ")
if os.path.exists(fName):
inFp = open(fName, "r", encoding="UTF-8")
inList = inFp.readlines()
for inStr in inList:
print(inStr, end = "")
inFp.close()
else :
print("%s 파일이 없습니다"%fName)
# 결과
파일명을 입력하세요: data.txt
CookBook 파이썬을 공부합니다.
완전 재밌어요
파이썬을 공부하기 잘했네요.
출력 결과를 파일에 저장하는 방식(파일에 내용 쓸 때 write()나 writelines() 함수 사용)
한 행씩 파일에 쓰기
outFp = None
outStr = ""
outFp = open("data2.txt","w")
while True:
outStr = input("내용 입력 : ")
if outStr != "":
outFp.writelines(outStr + "\n")
else:
break
outFp.close()
print("---파일에 정상적으로 써졌음 ---")
도스 copy 명령어의 구현
copy 소스파일 타깃파일
chr(i) : 유니코드(Unicode) 값을 입력받아 그 코드에 해당하는 문자를 출력하는 함수이다.
ord(c) : 문자 c의 유니코드 값을 돌려주는 함수이다.
(ord <-> chr)
readline()과 readlines() 함수
readlines() 함수 : 파일 용량이 몇 MB정도면 사용
readline() 함수 : 수백 MB가 넘으면 사용
간단한 파일 처리
with~as
문을 사용하면 텍스트 파일 복사 소스가 간단해진다.
inFp, outFp = None, None
inStr = ""
with open("C:/Windows/win.ini","r") as inFp:
with open("C:/Temp/data4.txt", "w") as outFp:
for inStr in inFp:
outFp.writelines(inStr)
print("---파일이 정상적으로 복사되었음 ---")
이진(Binary : 바이너리) 파일 : 글자가 아닌 비트(Bit) 단위로 의미가 있는 파일
텍스트 파일과 이진 파일을 구분하는 간단한 방법(파일을 메모장에서 열기)
이진 파일의 복사
inFp, outFp = None, None
inStr = ""
# 이진 읽기 모드와 쓰기 모드로 파일 열기
inFp = open("C:/Windows/notepad.exe","rb")
outFp = open("notepad.exe","wb")
# 파일의 끝까지 한 바이트씩 읽어서 한 바이트씩 파일에 쓰기
while True:
inStr = inFp.read(1)
if not inStr:
break
outFp.write(inStr)
inFp.close()
outFp.close()
print("--- 이진 파일이 정상적으로 복사되었음 ---")
파일 및 디렉터리 다루기
shutil 모듈과 os 모듈, os path 모듈 : 파일, 디렉터리(폴더) 다룰 수 있는 다양한 함수 제공
shutil 모듈 : 파일과 파일 모음에 대한 여러 가지 고수준 연산을 제공. 특히, 파일 복사와 삭제를 지원하는 함수가 제공된다.
파일 및 디렉터리 복사
shutil.copy(소스파일, 타깃파일)함수 사용
shutil.copytree('C:/CookPython/GIF/','C:/Temp/GIF')
디렉터리의 생성 및 삭제
디렉터리의 생성 : os.mkdir(폴더명) 함수 사용
디렉터리의 삭제 : shutil.rmtree(폴더 명) 함수 사용
import os
import shutil
os.mkdir('C:/myDir/')
os.mkdir('C:/myDir/dir1/')
shutil.rmtree('C:/myDir/') # 폴더 안의 모든 파일 삭제
os.mkdir('C:/myDir/')
실행하지 않고 os.mkdir('C:/myDir/dir1/')
실행시 오류 발생
디렉터리의 목록 모두 보기
import os
for dirName, subDiList, fnames in os.walk('C:\Windows\debug'):
for fname in fnames:
print(os.path.join(dirName, fname))
파일 또는 폴더가 이미 존재하는지 확인
os.path.exists(파일명 또는 폴더명) 사용
os.remove('파일명 또는 폴더명') : 삭제
os.path.getsize('파일명 또는 폴더명') : 파일 크기
파일 압축과 압축 풀기
import zipfile
newZip = zipfile.ZipFile('C:/Temp/new.zip','w') # 새로 압축될 파일을 쓰기로 준비
newZip.write('C:/Windows/notepad.exe','compress_type = zipfile.ZIP_DEFLATED')
# 압축 수행
newZip.close() # 압축 파일 닫기
# 압축 풀기
extZip = zipfile.Zipfile('C:/Temp/new.zip','r') # 압축 풀 파일을 읽기로 준비
extZip.extractall('C:/Temp/') # 해당 폴더에 압축 풀기
extZip.close() # 압축 파일 닫기
try, except 문
예외 처리(Exception Handing) : 오류가 발생할 때 파이썬이 처리하지 않고 프로그래머가 작성한 코드를 실행하는 방식
try :
os.remove('C:/Temp/noFile.exe')
except :
print('파일이 없네요. 확인 바랍니다.')
ex) 문자열 중에서 '파이썬' 글자의 위치를 모두 찾아서 출력하는 코드
myStr = '파이썬은 재미 있어요. 파이썬만 매일매일 공부하고 싶어요.'
strPosList = []
index = 0
while True:
try:
index = myStr.index('파이썬',index)
strPosList.append(index)
index = index + 1 # 다음 위치부터 찾음
except:
break
print('파이썬 글자 위치 --->', strPosList)
except 문 뒤에 아무것도 명시하지 않으면 모든 종류의 오류 처리
try, except, else, finally 문
raise 문
raise들 이용하여 예외 강제로 발생 가능
raise문에 의해서 Exception이 발생되어 파이썬 인터프리터 프로그램이 그 과정을 추적하였다는 출력이 뜬다.
raise Exception('Exception raised')
raise Exception('예외 발생!')
get_ans() 함수
def get_ans(ans):
if ans in ['예','아니오']:
print('정상적인 입력입니다.')
else:
raise valueError('입력을 확인하세요.')
while True:
try:
ans = input('예/아니오 중 하나를 입력하세요.')
get_ans(ans)
break
except Exception as e:
print('error :', e)
with ~ as 구문
with 문법
__enter__()
과 __exit__()
함수를 정의하여, with 구문 몸체의 앞부분과 뒷부분에 실행되는 코드를 대신해준다.f = open('hello.txt','w') # 파일 열기
f.write('Hello World!') # hello.txt 파일에 쓰기
f.close() # 파일을 닫는다.
f = open('hello.txt','w') # 파일 열기
try:
f.write('Hello World!') # hello.txt 파일에 쓰기
finally:
f.close() # 파일을 닫는다.
with open('hello.txt','w') as f: # 파일 열기와 닫기를 자동 수행한다.
f.write('Hello World!') # hello.txt 파일에 쓰기
import urllib.request
with urllib.request.urlopen('http://python.org/') as response:
html = response.read()
print(html)
try-except-else 문
try-except 문을 사용한 파일 입출력
import sys
fname = input('입력할 파일의 이름 : ')
try :
f = open(fname, 'r', encoding = 'UTF8') # 파일 열기
except IOError:
print('Could not read file:',fname)
sys.exit()
except:
print('Unexpected error:',sys_exc_info()[0])
sys.exit()
n = 1 # n을 1로 초기화 한다.
l = f.readline() # 변수 l은 읽어들인 한 줄의 문자열을 저장한다.
while l :
print('{:3d}: {}'.format(n, l), end='')
n += 1 # 한 줄을 출력한 후 줄 수를 증가시킨다.
l = f.readline() # 다음 줄을 읽어온다.
f.close()
참고 자료