Python은 txt 파일을 읽습니다.

기사 디렉토리

1. 준비

파일 이름은 "info.txt"이고
파일 내용은 다음과 같습니다.

Python 언어 학습에 오신 것을 환영합니다
1 장 : Python 과거 및 현재
2 장 : Python 언어 기본 사항
3 장 : Python 고급 고급

2. 코드

text_file = open('info.txt', 'rt', encoding='utf-8')
for line in text_file.readlines():
    print(line, end='')
text_file.close()

또는

text_file = open('info.txt', 'rt', encoding='utf-8')
content = text_file.read()
print(content)
text_file.close()

또는

with open('info.txt', 'rt', encoding='utf-8') as text_file:
    content = text_file.read()
    print(content)

또는

with open('info.txt', 'rt', encoding='utf-8') as text_file:
    for line in text_file.readlines():
        print(line, end='')

3. 결과

오픈 러닝 결과

4. 설명

내 환경에서 "encoding = utf-8"매개 변수가 없으면 오류가보고됩니다.
오류 내용은 다음과 같습니다. UnicodeDecodeError : 'gbk'codec ca n't decode byte 0xad in position 20 : invalid multibyte sequence

추천

출처blog.csdn.net/PursueLuo/article/details/105704219