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]

4

3 回答 3

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. 如果您想将这些行存储在 a 中list,请尝试列表推导:

selected_lines = [lines[index] for index in sortrule]
于 2013-03-29T15:45:12.387 回答
0

你可以做这样的事情。

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

这会给你一个由 \n 分隔的行列表

于 2013-03-29T15:47:43.933 回答
0

在您的情况下,您只需要一个一维数组,因此列表就足够了。并且您的代码已经将每一行存储到列表变量行中。

于 2013-03-29T15:52:37.840 回答