2016-05-17 121 views
0

我想讀取python中的文本文件。該文件的第一行僅僅是文件的名稱,並且該文件的每一行都包含一個實數。我是python的新手,試圖解析文件並將數字保存在一個數組中(忽略第一行)。任何幫助將不勝感激。謝謝。將文本文件中的數據保存到Python中的數組中

回答

2

試試這個,

with open(filename, 'r') as f: 
    next(f) # discard the first line 
    l = [int(line) for line in f] # save numbers to a list 

閱讀第n行,使用itertools.islice

import itertools 

with open(filename, 'r') as f: 
    lines_gen = itertools.islice(f, 1, num_lines) # start from 1, read num_lines 
    l = [int(line) for line in lines_gen] 
+0

這似乎工作正常。但是,在501行數據之後,還有另一行是一個字符串。我能否以任何方式創建一個從第2行開始到第500行結束的數組? – Aspro

+1

你並不需要'rstrip()'調用,'int'可以處理尾隨空格。 – martineau

+0

@Arya,試試這個,'l = [int(line)for line in f.readlines [2:501]]' – SparkAndShine

2

打開它,跳過第一行,然後將剩下的映射到整​​數(使用list()調用將其保存在內存中 - 只有在您打算多次檢查或更改它時才需要)。

with open('f.txt') as f: 
    next(f) 
    data = list(map(int, f)) 
+0

這是一個非常pythonic的方式!我建議使用這一個。請注意,下一步的使用是針對python 3.對於python 2,請使用f。 readline() – silviomoreto

+2

@silvio:'next(f)'在Python 2中也能正常工作。 – martineau

1

你可以這樣做:

your_array = [] 
with open('arrayfile.txt', 'r') as f: 
    f.readline() # skip first line 
    for number in f: 
     your_array.append(int(number)) 
相關問題