Programing

파이썬으로 텍스트 파일을 목록이나 배열로 읽는 방법

lottogame 2020. 7. 7. 07:41
반응형

파이썬으로 텍스트 파일을 목록이나 배열로 읽는 방법


파이썬에서 텍스트 파일의 행을 목록이나 배열로 읽으려고합니다. 목록이나 배열의 항목을 만든 후 개별적으로 액세스 할 수 있어야합니다.

텍스트 파일의 형식은 다음과 같습니다.

0,0,200,0,53,1,0,255,...,0.

(가) 어디 ...위이며, 실제 텍스트 파일이 수백 또는 수천 이상의 항목이 있습니다.

다음 코드를 사용하여 파일을 목록으로 읽으려고합니다.

text_file = open("filename.dat", "r")
lines = text_file.readlines()
print lines
print len(lines)
text_file.close()

내가 얻는 결과는 다음과 같습니다.

['0,0,200,0,53,1,0,255,...,0.']
1

분명히 전체 파일을 개별 항목 목록이 아닌 하나의 항목 목록으로 읽습니다. 내가 뭘 잘못하고 있죠?


다음을 사용하여 문자열을 값 목록으로 분할해야합니다. split()

그래서,

lines = text_file.read().split(',')

python의 file.readLines () 메소드는 파일의 행 목록을 리턴합니다.

f = open('file_name.ext', 'r')
x = f.readlines()
f.close()

이제 x 행의 배열을 반복 할 수 있어야합니다.

파일을 사용하고 나중에 파일을 닫을 필요가없는 경우 다음을 수행하십시오.

with open('file_name.ext', 'r') as f:
    x = f.readlines()

다음과 같이 numpy loadtxt를 사용할 수도 있습니다.

from numpy import loadtxt
lines = loadtxt("filename.dat", comments="#", delimiter=",", unpack=False)

리스트의리스트를 만들려고합니다. 빈리스트로 시작해야합니다

list_of_lists = []

다음으로 파일 내용을 한 줄씩 읽습니다.

with open('data') as f:
    for line in f:
        inner_list = [elt.strip() for elt in line.split(',')]
        # in alternative, if you need to use the file content as numbers
        # inner_list = [int(elt.strip()) for elt in line.split(',')]
        list_of_lists.append(inner_list)

일반적인 유스 케이스는 컬럼 데이터의 경우이지만 스토리지 단위는 파일의 행이며, 우리는 하나씩 읽었으므로 목록 목록 바꾸고 싶을 수 있습니다 . 이것은 다음 관용구로 수행 할 수 있습니다

by_cols = zip(*list_of_lists)

또 다른 일반적인 용도는 각 열에 이름을 지정하는 것입니다

col_names = ('apples sold', 'pears sold', 'apples revenue', 'pears revenue')
by_names = {}
for i, col_name in enumerate(col_names):
    by_names[col_name] = by_cols[i]

동종 데이터 항목에서 작업 할 수 있도록

 mean_apple_prices = [money/fruits for money, fruits in
                     zip(by_names['apples revenue'], by_names['apples_sold'])]

내가 작성한 대부분의 내용 csv은 표준 라이브러리에서 모듈 을 사용하여 속도를 높일 수 있습니다 . 또 다른 타사 모듈은 pandas일반적인 데이터 분석의 여러 측면을 자동화 할 수 있지만 여러 가지 종속성이 있습니다.


Update While in Python 2 zip(*list_of_lists) returns a different (transposed) list of lists, in Python 3 the situation has changed and zip(*list_of_lists) returns a zip object that is not subscriptable.

If you need indexed access you can use

by_cols = list(zip(*list_of_lists))

that gives you a list of lists in both versions of Python.

On the other hand, if you don't need indexed access and what you want is just to build a dictionary indexed by column names, a zip object is just fine...

file = open('some_data.csv')
names = get_names(next(file))
columns = zip(*((x.strip() for x in line.split(',')) for line in file)))
d = {}
for name, column in zip(names, columns): d[name] = column

This question is asking how to read the comma-separated value contents from a file into an iterable list:

0,0,200,0,53,1,0,255,...,0.

The easiest way to do this is with the csv module as follows:

import csv
with open('filename.dat', newline='') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=',')

Now, you can easily iterate over spamreader like this:

for row in spamreader:
    print(', '.join(row))

See documentation for more examples.


If your file contains numerical values then numpy's loadtxt method seems to be the best approach. You can read the array as follows:

import numpy as np

filename = '../data/NLPR_MCT/db3/cam1.dat'
x = np.loadtxt(filename, delimiter=',')
print (x)

You can index values as array in x and file.readlines() is inconvenient because it inserts '\n' in every line and indexing may become erroneous.


with open('D:\python\positive.txt', 'r') as myfile: data=myfile.read().replace('\n', '')

참고URL : https://stackoverflow.com/questions/14676265/how-to-read-a-text-file-into-a-list-or-an-array-with-python

반응형