파일 읽기
파일 열기
open()- 변수명 = open(“파일경로/파일이름”, “모드(용도)”)
| mode | 설명 |
|---|---|
| r | 읽기(default) |
| w | 쓰기 파일이 없으면 새파일 생성 파일이 있으면 초기화 후 덮어쓰기 |
| x | 새 파일 생성, 기존파일 있으면 작업 실패 |
| b | 바이너리 모드에서 열기 |
| + | 읽기 및 쓰기를 위해 파일 열기 |
파일 읽기
변수.readline()- 파일 내용을 한 줄씩 읽기
inFile = None #파일 인스턴스 초기화
inStr = "" #문자열 인스턴스 초기화
inFile = open("C:/myFolder/myFile.txt", "r", encoding="UTF-8")
inStr = inFile.readline()
print(inStr, end='') #파일 내 개행문자 포함, 추가 개행을 하지 않음
inStr = inFile.readline() #커서 이동
print(inStr, end='')
inStr = inFile.readline() #커서 이동
print(inStr, end='')
inFile.close()
변수.readlines()- 파일 내용을 한꺼번에 읽어 리스트에 저장
inFile = None
inList = []
inFile = open("C:/myFolder/myFile.txt", "r", encoding="UTF-8")
inList = inFile.readlines()
for inStr in inList:
print(inList, end="")
inFile.close()
파일 닫기
변수.close()
:
파일 쓰기
변수.writelines()- 입력 내용이 모니터에 나오지 않고 파일에 직접 저장
- 같은 파일에 입력 시 새로운 내용으로 덮어씀
Ex Ctrl+C - Ctrl+V 실습
openGreetings = None
writeGreetings = None
openGreetings = open("C:/Documents/reetings.txt","r", encoding="UTF-8")
writeGreetings = open("C:/Documents/newGreetings.txt","w")
greet = ""
while True:
greet = openGreetings.readline()
if greet =="":
break
writeGreetings.writelines(greet)
openGreetings.close()
writeGreetings.close()
파일 위치 경로 \(역슬래시) ⇒ /(슬래시)로 수정
Ex 암호화 실습
- ord(str) : 문자의 고유 숫자 반환
- chr(num) : 고유 숫자에 해당하는 문자 반환
saveFile = open("C:/myFolder/myFile/encryptedMSG.txt","w")
savedMsg = ""
encrptedMsg=""
while True:
saveddMsg = input("전달 메시지")
if savedMsg == "":
break
for ch in saveMsg:
encrptedMsg+=chr(ord(ch)+123)
saveFile.writelines(encrptedMsg+"\n")
saveFile.close()
Ex setup.cfg 파일 설정 치환
객체 지향 프로그래밍
- 객체(Object)
- 특정 속성(변수)과 행동(메소드)을 가진 데이터
- 클래스
- 객체를 생성하기 위한 틀
class clsName:
# 클래스 생성 코드
obj1 = clsName #객체 생성
obj.attr # 속성 접근
obj.mthd() # 메서드 호출
class tokki:
shape = "default"
color = "white"
x=0
y=0
def move(self, _x, _y):
self.x = _x
self.y = _y
def goto(self, _x, _y):
self.x +=_x
self.y +=_y
ttk = tokki
ttk.shape = "뚱뚱"
ttk.color = "red"
ttk.move(40,29)
ttk.goto(13,20)