10장. 파일 읽고 쓰기
- 입출력 함수
- input(), print()
- read(), readline(), readlines()
- write(), writelines()
- 파일
- 파일 열기 : 변수명 = open(“파일명”, “모드”)
- 파일 닫기 : 변수명.close()
- 파일 쓰고 읽기 : 10_01_FileInOut.py
1234567891011121314151617# -*- coding:utf-8 -*-fp = open("file.txt", "a", encoding="utf-8")buf = input() # buf = "안녕하세요"fp.writelines(buf + "\n")fp.close()fp = open("file.txt", "r", encoding="utf-8")bufList = fp.readlines()for buf in bufList:print(buf, end="")# while True:# buf = fp.readline()# if buf == "":# break# print(buf, end="")fp.close() - 파일 존재 여부 판단 : if os.path.exists(filename) :
- 파일 열기 : 변수명 = open(“파일명”, “모드”)
- 문자 <-> 숫자 변환 함수
- ord() : 문자의 고유 숫자를 리턴
- chr() : 고유 숫자에 해당하는 문자를 리턴
- 이진 파일 복사
12345678910111213# -*- coding:utf-8 -*-inFp = open("img/jj.gif", "rb")outFp = open("img/kk.gif", "wb")buf = ""while True:buf = inFp.read()if not buf:breakoutFp.write(buf)inFp.close()outFp.close() - Lena.raw 파일 읽어 Canvas에 출력하기 : 10_11_ViewRawLena.py
12345678910111213141516171819# -*- coding:utf-8 -*-from tkinter import *window = Tk()canvas = Canvas(window, width=256, height=256)photo = PhotoImage(width=256, height=256)canvas.create_image((128, 128), image=photo, state="normal")fp = open("img/lena.raw", "rb")for y in range(0, 256):for x in range(0, 256):data = int(ord(fp.read(1)))photo.put("#%02x%02x%02x" % (data, data, data), (x, y))fp.close()canvas.pack()window.mainloop()