【问题标题】:.readlines() shouldn't return an array?.readlines() 不应该返回一个数组?
【发布时间】:2016-10-13 13:29:58
【问题描述】:

.readlines() 有问题。 它过去只返回指定的行,即如果我跑了

f1 = open('C:\file.txt','r')
filedata = f1.readlines(2)
f1.close()
print filedata

它应该打印 file.txt 的第二行。 但是现在当我运行相同的代码时,它会在一个数组中返回文件的全部内容,文件中的每一行都是数组中的一个单独的对象。我使用的是同一台 PC,并且运行的是同一版本的 python (2.7).

有人知道解决这个问题的方法吗?

【问题讨论】:

  • readlines 的参数是关于使用什么大小的缓冲区的提示,内置的file 类型可能会忽略它。这不是对特定线路的请求。

标签: python readlines


【解决方案1】:

不要使用readlines;它将整个文件读入内存,然后选择所需的行。相反,只需阅读前n 行,然后中断。

n = 2
with open('C:\file.txt','r') as f1:
    for i, filedata in enumerate(f1, 1):
        if i == n:
            break
print filedata.strip()

itertools documentation 还提供了使用序列的前 n 项的配方:

def consume(iterator, n):
    "Advance the iterator n-steps ahead. If n is none, consume entirely."
    # Use functions that consume iterators at C speed.
    if n is None:
        # feed the entire iterator into a zero-length deque
        collections.deque(iterator, maxlen=0)
    else:
        # advance to the empty slice starting at position n
        next(islice(iterator, n, n), None)

你可以这样使用它:

n = 2
with open('C:\file.txt','r') as f1:
    consume(f1, n-1)
    filedata = next(f1)
print filedata.strip()

【讨论】:

    【解决方案2】:

    改变这个:

    f1.readlines(2)
    

    到这里:

    f1.readlines()[2]
    

    【讨论】:

    • Traceback(最近一次调用最后):文件“\\8865460-fp01\EU_HomeFolders\ITExam57\Troubleshooter CAU\Task2\Task2.py”,第 7 行,在 filedata = f1.readlines [1] TypeError: 'builtin_function_or_method' 对象不可下标
    • 啊,帕特里克解决方案修复了它。非常感谢你们的帮助。
    猜你喜欢
    • 1970-01-01
    • 2017-06-11
    • 1970-01-01
    • 2017-05-18
    • 2018-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多