본문 바로가기
C++ 200제/코딩 IT 정보

파이썬 파일 읽기 (utf-8 txt) 방법 7가지 예제

by vicddory 2019. 6. 7.

먼저 파이썬 파일 읽기 예제에 사용할 txt 파일을 만듭니다. 메모장을 열어 텍스트 파일에 아무 내용이나 채워 주세요. 그리고 왼쪽 상단 메뉴에서 "파일(F) - 다른 이름으로 저장(A)"을 선택합니다.


그리고 인코딩(E) 방식을 UTF-8로 지정하고 저장 버튼을 눌러 주세요.



생성한 txt 파일은 파이썬 파일과 같은 경로로 이동해 주세요. 파이썬 파일 읽기 (utf-8) 7가지 예제 소개합니다.


1. for 반복문


1
2
3
4
5
6
7
8
9
10
11
def showFile_1(filename):
    f = open(filename, 'r', encoding='utf-8')    # euc-kr
 
    lines = f.readlines()
 
    for line in lines:
        print(line, end='')
 
    f.close()
 
showFile_1('test.txt')
cs


2번 라인 open 함수에서 'r'은 읽기 전용, encoding은 utf-8입니다.


■ 결과


파이썬 파일 읽기파이썬 파일 읽기


2. while 반복문


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def showFile_2(filename):
    f = open(filename, 'r', encoding='utf-8')
 
    while True:
        line = f.readline()
 
        # if not line:
        if len(line) == 0:
            print('=end=', line, type(line), sep='')
            break
 
        print(line, end='')
 
    f.close()
 
showFile_2('test.txt')
cs


■ 결과



3. while 반복문 + strip


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def showFile_3(filename):
    f = open(filename, 'r', encoding='utf-8')
 
    while True:
        line = f.readline()
 
        if not line:
            break
 
        line = line.strip()
        print(line)
 
    f.close()
 
showFile_3('test.txt')
cs


■ 결과


파이썬 파일 읽기파이썬 파일 읽기


4. for 반복문


1
2
3
4
5
6
7
8
9
def showFile_4(filename):
    f = open(filename, 'r', encoding='utf-8')
 
    for line in f:
        print(line, end='')
 
    f.close()
 
showFile_4('test.txt')
cs


■ 결과


파이썬 파일 읽기파이썬 파일 읽기

5. 쓰기


1
2
3
4
5
6
7
8
def showFile_5(filename):
    f = open(filename, 'w')
 
    f.write('hello, everyone')
 
    f.close()
 
showFile_5('test.txt')
cs


■ 결과


문서파일 utf-8 읽기문서파일 utf-8 읽기 쓰기


6. try except


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
def showFile_6(filename):
    try:
        f = open(filename)
 
        for line in f:
            print(line, end='')
 
        f.close()
    except FileNotFoundError as e:
        print(e)
    except:
        print('Unknown error')
    finally:
        if not f.closed:
            f.close()
 
showFile_6('test.txt')
cs


■ 결과


파이썬 파일 읽기파이썬 파일 읽기


7. with as


1
2
3
4
5
6
7
8
def showFile_7(filename):
    with open(filename) as f:
        for line in f:
            print(line, end='')
 
    print('closed :', f.closed)
 
showFile_7('test.txt')
cs


■ 결과


문서파일 utf-8 읽기




관련 글


파이썬 정렬 sort sorted reverse=true 예제 4개


파이썬 정렬 소스, 숫자 문자열 예제 6개 sorted join


파이썬 print 재귀함수, 반복 출력, 문자열 거꾸로 뒤집기



ⓒ written by vicddory

댓글