728x90
텍스트 파일 불러오는 법
open(filename.txt, mode)
mode | description |
"r" | Read, 읽기 모드 |
"w" | Write, 쓰기 모드 (파일 존재할 시 새로 쓰기) |
"a" | Append, 추가 모드, 기존 파일에 내용 추가할 때 사용 |
"x" | Create, 파일 생성 (파일 존재할 시 에러) |
1. 파일 새로 생성하여 쓰기
f = open("file.txt","w")
f.write("hello, world!\n")
f.close()
결과
2. 파일에 내용 추가하기
f = open("file.txt","a")
f.write("I'm hungry.")
f.close()
결과
3. with문 사용하여 파일 불러오기
- with문 안에서만 open이 실행되있으므로, 따로 close를 해줄 필요가 없습니다.
with open("file.txt", "r") as f:
lines = f.readlines()
for line in lines:
print(line)
결과
'프로그래밍 > Python' 카테고리의 다른 글
[파이썬, Python] 파일, 디렉토리 경로 관련 함수 (os, os.path) (0) | 2023.01.17 |
---|---|
[파이썬, Python] csv 파일 불러오기 (open, close, with) (0) | 2023.01.17 |
[파이썬, Python] plot style 변경 (0) | 2023.01.17 |
[파이썬, Python] 이중 for 문 한 줄로 만들기 (0) | 2023.01.17 |
[파이썬, Python] log 남기기 (logging, VSCode) (0) | 2022.10.23 |