업무에 파이썬 활용할 줄 알기
Day24 | 파일과 디렉토리, 경로 본문
뱀게임에 최고 점수 추가하기
high score 추가하고
뱀이 벽이나 꼬리와 부딪혀서 게임오버 되던 걸
게임오버 시키지 않고, 게임을 다시 리셋시키도록 변경
→ scoreboard.game_over() 삭제, game_is_on=False 삭제
→ scoreboard.reset() 추가
→ snake.reset() 추가
→ snake.reset() 메서드에 죽은 뱀 화면 바깥으로 보내기, segments 리스트 clear() 하기
추가 문제해결 상황
문제상황: 파이썬에서 게임을 다시 시작하면 기존의 high_score 기록이 다시 0으로 돌아감
해결과제: high_score 기록을 어딘가에 남겨놓고 값을 가져오도록 하는 것
"With" 키워드 사용 방법
read, write 부터 해보기
파일을 열고,읽고, 우리가 읽어온 컨텐츠를 프린트하기
그리고 file.close()까지 해주어서 컴퓨터 리소스를 아낄 수 있도록 해주어야한다


그치만 open()과 close()사이에 수많은 작업들이 들어갈테고, 그러면 close()문 작성을 잊어버릴 수도 있기 때문에
프로그래머들은 'with' 키워드를 사용하여 파일을 열어준다.
'with'키워드는 일이 끝났다는 것을 알아차리는 즉시, 파일을 닫는다.
with open("my_file.txt") as file:
contents = file.read()
print(contents)
my_file.txt에 새로운 텍스트 입력하기
mode = "w" (write)로 설정해주어야 함
그렇지 않으면 읽기모드로 디폴트 세팅이 되어있어 오류 남
with open("my_file.txt", mode="w") as file:
file.write("New text.")
my_file.txt에 기존 텍스트 지우지 않고, 새로운 텍스트 추가하기
mode = "a" (append)로 설정해주어야 함
with open("my_file.txt", mode="a") as file:
file.write("\nNew text.")
새로운 파일 생성하기
mode="w"으로 해주어야 새로운 파일을 생성할 수 있다

도전 과제: 뱀게임에서 파일에 최고 점수 읽고 쓰기
위에서 배운 txt파일에 저장하고, 데이터 불러오는 방법 적용하기
상대 및 절대 파일 경로에 대한 이해
파일은 이름만 가지고 있지 않다. 경로를 함께 가지고 있다.
파일은 폴더안에있고, 특정 파일을 찾기위해서는 폴더들을 탐색해야한다.
- 절대 파일 경로
루트를 기준으로 시작 (Mac: /, Microsoft: /C:)
컴퓨터 저장 시스템의 근원이 되는 지점에서 시작하는 경로
- 상대 파일 경로
현재 작업하고 있는 디렉토리와 관련있음, 어디에 있고, 어디에 도달하고 싶은지에 달려있음
'./' 현재 폴더, 즉 working directory를 뜻함
'..' 부모 폴더로 가는 계층 구조에서 한 단계 위로 가라는 뜻
Challenge1) working directory에 있던 txt파일을 desktop으로 옮기고, 절대 파일 경로로 수정하기
Challenge2) main.py의 위치에서 바탕화면에 있는 new_file.txt로 도달하려면? 상대 파일 경로로 수정하기
main.py의 경로: C:\Users\user\PycharmProjects\day-24
new_file.txt의 경로: C:\Users\user\OneDrive\바탕 화면
Q) 상대 파일 경로를 사용해서 어떻게 2개의 폴더 뒤로 점프해서
user폴더로 가고 그 다음엔 Desktop으로, 그런 다음 new_file.txt 까지 도달할 수 있을까요?
→ A) ../ 그리고 ../로 2단계 위로 올라간 다음 new_file.txt가 있는 바탕화면으로 다시 내려가면 된다.
메일 머지 Challenge
My solution
#TODO: Create a letter using starting_letter.txt
#for each name in invited_names.txt
#Replace the [name] placeholder with the actual name.
#Save the letters in the folder "ReadyToSend".
#Hint1: This method will help you: https://www.w3schools.com/python/ref_file_readlines.asp
#Hint2: This method will also help you: https://www.w3schools.com/python/ref_string_replace.asp
#Hint3: THis method will help you: https://www.w3schools.com/python/ref_string_strip.asp
#최종결과: 이름 변경한 편지들 파일 하나씩 생성하기
#starting_letter.txt에서 편지를 읽어온다
# with open('./Input/Letters/starting_letter.txt') as sl:
# sl = sl.read()
with open('./Input/Letters/starting_letter.txt') as sl:
sl = sl.read()
#invieted_name.txt의 이름을 리스트화해준다
names = open('./Input/Names/Invited_names.txt', "r")
names_raw = names.readlines()
name_list = []
for name in names_raw:
new_name = name.replace('\n', '')
name_list.append(new_name)
#[]를 invited_names.txt의 이름으로 변경한다
#letter_to_name.txt 파일을 하나 생성하여 ReadyToSend에 저장해준다
for name in name_list:
new_letter = sl.replace('[name]', name)
with open(f"./Output/ReadyToSend/letter_to_{name}.txt", mode="w") as new_file:
new_file.write(new_letter)
해법과 설명: 메일 머지 프로젝트
Angela's solution
'name\n'이걸 나는 문자로 인식해서 replace() 하도록했는데, 그냥 strip()을 써도 되는거였다.
PLACEHOLDER = "[name]"
with open("./Input/Names/invited_names.txt") as names_files:
names = names_files.readlines()
with open("./Input/Letters/starting_letter.txt") as letter_file:
letter_contents = letter_file.read()
for name in names:
stripped_name = name.strip()
print(stripped_name) #test
new_letter = letter_contents.replace(PLACEHOLDER, stripped_name)
with open(f"./Output/ReadyToSend/letter_for_{stripped_name}.txt", mode="w") as completed_letter:
completed_letter.write(new_letter)
'Python > [Udemy] 100개의 프로젝트로 Python 개발 완전 정복' 카테고리의 다른 글
Day23 | 중급 | 터틀 크로싱 프로젝트 (0) | 2024.01.17 |
---|---|
Day22 | 중급 | 벽돌깨기의 시초, 퐁 게임 만들기 (0) | 2024.01.11 |
Day21 | 중급 | 뱀 게임 만들기 2편: 클래스 상속 & 리스트 슬라이싱 (2) | 2024.01.08 |
Day20 | 중급 | 뱀 게임 만들기 1편: 애니메이션 & 좌표 (0) | 2024.01.04 |
Day19 | 중급 | 인스턴스, 상태 및 고차함수 (0) | 2024.01.03 |