如何在Python中从.txt文件加载特定行?

如何在Python中从.txt文件加载特定行?

问题描述:

说我有一个.txt文件,其中包含许多行和列的数据以及一个包含整数值的列表.如何在文本文件中加载与列表中的整数匹配的行号?

Say I have a .txt file with many rows and columns of data and a list containing integer values. How would I load the row numbers in the text file which match the integers in the list?

为说明起见,假设我有一个整数列表:

To illustrate, say I have a list of integers:

a = [1,3,5]

如何将文本文件中的第1、3和5行读入数组?

How would I read only rows 1,3 and 5 from a text file into an array?

numpy中的loadtxt例程让您既跳过行又使用特定的列.但是我似乎找不到一种方法来做一些事情(忽略不正确的语法):

The loadtxt routine in numpy let's you both skip rows and use particular columns. But I can't seem to find a way to do something along the lines of (ignoring incorrect syntax):

new_array = np.loadtxt('data.txt', userows=a, unpack='true')

谢谢.

给出此文件:

1,2,3
4,5,6
7,8,9
10,11,12
13,14,15
16,17,18
19,20,21

您可以使用csv模块获取所需的np数组:

You can use the csv module to get the desired np array:

import csv
import numpy as np

desired=[1,3,5]
with open('/tmp/test.csv', 'r') as fin:
    reader=csv.reader(fin)
    result=[[int(s) for s in row] for i,row in enumerate(reader) if i in desired]

print(np.array(result))   

打印:

[[ 4  5  6]
 [10 11 12]
 [16 17 18]]