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

2024-09-28 20:45:11 发布

您现在位置:Python中文网/ 问答频道 /正文

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]


Tags: 文件oftheindextime数组datthere
3条回答

在你的例子中,你只需要一个一维数组,所以一个列表就足够了。您的代码已经将每一行存储到列表变量行中。你知道吗

您发布的代码将输入文件的行放入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]

你可以这样做。你知道吗

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

这将为您提供一个由\n分隔的行列表

相关问题 更多 >