파이썬에서 파일을 읽고 써보자
🐊 파일 읽기
"""
# 파일 여는 내장 함수
file = open("my_file.txt")
# 파일 읽기 변수에 파일 저장
contents = file.read()
print(contents)
# 파일 닫기 - 파일 열면 리소스 자원 사용중이라서 성능에 부하 줄 수 도 있음
file.close()
"""
# 위의 주석과 동일한 코드 - close 생략 가능
with open("my_file.txt") as file :
contents = file.read()
print(contents)
🐊 실행 결과

🐊 파일 수정
# 읽기모드:r, 편집모드:w
with open("my_file.txt", mode="w") as file :
# 텍스트 변경
contents = file.write("change change change")
🐊 실행 결과

🐊 내용 추가
# 추가하기 : a
with open("my_file.txt", mode="a") as file :
# 텍스트 변경
contents = file.write("\n hey new :/")
🐊 실행 결과

🐊 파일 생성
# 쓰기 모드에서 파일이 없으면 파일을 새로 생성
with open("new_file.txt", mode="w") as file :
# 텍스트 변경
contents = file.write("i'm rola ~~~~~~~")
🐊 실행 결과

머 이렇습니다요
'Python 🎧' 카테고리의 다른 글
| [python] pandas 라이브러리 기본 사용법 - csv/to_dict/to_list/DataFrame (3) | 2024.09.03 |
|---|---|
| [python] 핵쉬운 초대장 자동 생성 - 파일/읽기/쓰기/with/open/replace/strip/readlines/절대경로/상대경로 (0) | 2024.09.03 |
| [python] 길 건너기 게임 - turtle/class/상속/예제 (1) | 2024.09.01 |
| [python] 핑퐁 게임 - turtle/class/상속/class/super/init (0) | 2024.08.31 |
| [Python] 간단 snake 게임 만들기 - 클래스/슬라이싱/상속 (0) | 2024.08.26 |