【问题标题】:getting data from a file and putting it into an array从文件中获取数据并将其放入数组
【发布时间】:2013-03-29 15:40:40
【问题描述】:
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]

【问题讨论】:

  • 您发布的代码符合您的要求。你有问题吗?
  • 我猜你回答了自己的问题
  • 它打印出行,它不把它放入一个数组中
  • 是的,它确实将它们放在一个数组中。它将它们放入lines
  • 或者,您是否只想将sortrule 选择的行放入数组中?

标签: python arrays file


【解决方案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]

【讨论】:

    【解决方案2】:

    你可以这样做。

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

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-10-02
        • 2014-07-10
        • 1970-01-01
        • 2014-01-02
        • 1970-01-01
        • 2023-03-26
        • 2020-10-02
        • 1970-01-01
        相关资源
        最近更新 更多