2013-03-29 200 views
0
with open('rules_test1Fold0w4_sample00ll1.dat') as fileobj: 
    lines = list(fileobj) 
actualrules='' 
for index in sortrule: 
    print lines[index] 

我有這段代碼打印出.dat文件的某些行,但是我想要做的是將每行都作爲陣列。 因此,舉例來說,如果我的文件中從文件中獲取數據並將其放入數組

`'Once upon a time there was a young 
    chap of the name of Peter he had a 
    great friend called Claus'` 

過這樣的陣列將[Once upon a time there was a young,chap of the name of Peter he had a,great friend called Claus]

+2

您發佈的代碼確實符合您的要求。你有問題嗎? –

+0

我想你回答了你自己的問題 – Mibou

+0

它打印出來的線條,它沒有把它放入數組 – miik

回答

0

你可以做這樣的事情。

with open('rules_test1Fold0w4_sample00ll1.dat') as fileobj: 
    lines = fileobj.readlines() 
actualrules='' 
for index in sortrule: 
    print lines[index] 

這將使您\ n

1

您發佈的代碼把輸入文件的行成list

>>> with open('/etc/passwd') as fileobj: 
... lines = list(fileobj) 
... 
>>> type(lines) 
<type 'list'> 
>>> lines[0] 
'root:x:0:0:root:/root:/bin/bash\n' 
>>> 

此外,您發佈的代碼有某種應用了選擇濾波器,打印出sortrule指定的線路。如果你想有存儲在list那些線,嘗試列表理解:

selected_lines = [lines[index] for index in sortrule] 
0

在你的情況分開行的列表,你只需要一個維數組,所以列表是足以。你的代碼已經將每行存儲到列表變量行中。

相關問題