2013-03-29 134 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

在你的情况分开行的列表,你只需要一个维数组,所以列表是足以。你的代码已经将每行存储到列表变量行中。

相关问题