从文件中获取数据并将其放入数组中

时间:2013-03-29 15:40:40

标签: python arrays file

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]

3 个答案:

答案 0 :(得分: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]

答案 1 :(得分:0)

你可以这样做。

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

这会给你一个由\ n

分隔的行列表

答案 2 :(得分:0)

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