Python에서 텍스트 파일을 목록으로 읽는 방법(예제 포함)


두 가지 방법 중 하나를 사용하여 Python에서 텍스트 파일을 목록으로 읽어올 수 있습니다.

방법 1: open() 사용

 #define text file to open
my_file = open(' my_data.txt ', ' r ')

#read text file into list
data = my_file. read ()

방법 2: loadtxt() 사용

 from numpy import loadtxt

#read text file into NumPy array
data = loadtxt(' my_data.txt ')

다음 예에서는 각 방법을 실제로 사용하는 방법을 보여줍니다.

예제 1: open()을 사용하여 텍스트 파일을 목록으로 읽어옵니다.

다음 코드는 open() 함수를 사용하여 my_data.txt 라는 텍스트 파일을 Python의 목록으로 읽어오는 방법을 보여줍니다.

 #define text file to open
my_file = open(' my_data.txt ', ' r ')

#read text file into list 
data = my_file. read ()

#display content of text file
print (data)

4
6
6
8
9
12
16
17
19

예제 2: loadtxt()를 사용하여 텍스트 파일을 목록으로 읽어옵니다.

다음 코드는 NumPy loadtxt() 함수를 사용하여 my_data.txt 라는 텍스트 파일을 NumPy 배열로 읽는 방법을 보여줍니다.

 from numpy import loadtxt

#import text file into NumPy array
data = loadtxt(' my_data.txt ')

#display content of text file
print (data)

[4. 6. 6. 8. 9. 12. 16. 17. 19.]

#display data type of NumPy array
print ( data.dtype )

float64

loadtxt() 사용의 장점은 dtype 인수를 사용하여 텍스트 파일을 가져올 때 데이터 유형을 지정할 수 있다는 것입니다.

예를 들어 NumPy 배열에 정수로 가져올 텍스트 파일을 지정할 수 있습니다.

 from numpy import loadtxt

#import text file into NumPy array as integer
data = loadtxt(' my_data.txt ', dtype=' int ')

#display content of text file
print (data)

[4 6 6 8 9 12 16 17 19]

#display data type of NumPy array
print ( data.dtype )

int64

참고 : 여기에서 loadtxt() 함수에 대한 전체 문서를 찾을 수 있습니다.

추가 리소스

다음 튜토리얼에서는 Python에서 다른 파일을 읽는 방법을 설명합니다.

NumPy로 CSV 파일을 읽는 방법
Pandas로 CSV 파일을 읽는 방법
Pandas로 텍스트 파일을 읽는 방법

의견을 추가하다

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다