[python]File Read
- 읽기모드:
r
- 쓰기모드:
w
- 추가모드:
a
- 텍스트모드:
t
(기본값) - 바이너리모드:
b
1. 경로
- 상대경로: 내가 있는 폴더 위치 중심에서 경로
- 절대경로: 내가 어디있든 파일경로
2. 파일 읽기(Read)
1) open을 통해 읽기
-
외부에 있는 파일 연결해주는 함수:
open
읽기모드(텍스트)로 가져와라
f = open('./resource/it_news.txt', 'r', encoding='UTF-8')
✏️ 읽는데 텍스트로 읽기=rt(기본값=r), 바이너리로 읽기 = rb -
속성확인
print(dir(f))
-
인코딩확인
print(f.encoding)
-
파일이름 확인
print(f.name)
-
모드 확인
print(f.mode)
-
문서 일기
cts = f.read()
print(cts)
- 열면 꼭 닫아주기!
f.close()
2) with문을 통해 읽기
-
close 하지 않아도 내부적으로 닫힘
-
읽기모드 열어서 전문 읽기
with open('./resource/it_news.txt', 'r', encoding='UTF-8') as f:
c = f.read()
print(c)
✏️ read()
: 전체 읽기, read(10)
: 10Byte만 읽기(영어는 1글자=1byte)
✏️ 파이썬은 내가 어디까지 읽었는지 알고있음!!(커서)
with open('./resource/it_news.txt', 'r', encoding='UTF-8') as f:
c = f.read(20)
print(c)
c = f.read(20)
print(c)
-
결과: Right now gamers can
pay just $1 for acc -
처음으로 돌아가기
f.seek(0,0)
3) 한줄씩 읽기
with open('./resource/it_news.txt', 'r', encoding='UTF-8') as f:
line = f.readline()
print(line)
4) readlines: 전체를 읽은 후 라인 단위 리스트로 저장
with open('./resource/it_news.txt', 'r', encoding='UTF-8') as f:
cts = f.readlines()
print(cts)
- readlines를 list로 변환 후 다시 원문으로
with open('./resource/it_news.txt', 'r', encoding='UTF-8') as f:
cts = f.readlines()
print(cts)
for c in cts:
print(c, end='')
Author And Source
이 문제에 관하여([python]File Read), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@anjaekk/TIL-12-python-File-Read저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)