【问题标题】:Remove whitespaces from speciifc part of file从文件的特定部分删除空格
【发布时间】:2014-07-25 17:07:31
【问题描述】:

代码:

with open(filename) as f:
    file_list = f.readlines()
    file_list = [line.strip() for line in file_list] # remove whitespaces from each line of file
    code to process data between start and end tags (these tags can have whitespaces thats why i have removed them above)

这段代码对我来说很好用,但是如果文件太大,那么我认为将整个数据复制到列表中然后从每一行中去除空格是不明智的。

如何删除列表特定部分的空格,以便我可以在列表中保存那么多部分?

我试过了:

with open(filename) as f:
    for line in f.readlines():
         if line.strip() == "start":
             start = f.readlines.index("start")
         if line.strip() == "end"
             end = f.readlines.index("end")
    file_list = f.readlines[start:end]

但它给出错误

start = f.readlines.index("start")
AttributeError: 'builtin_function_or_method' object has no attribute 'index'

我只是想写一篇文章开头提到的高效代码。

【问题讨论】:

  • 我可以告诉您,您的第二个 readlines() 将失败,因为第一个将文件指针留在文件末尾:没有更多行可读取。但是,如果您需要帮助,您需要努力告诉人们您的问题是什么。
  • file_list = f.readlines().strip() "这段代码对我来说很好用" -- 你确定吗?我原以为这会出错,因为上次我检查你不能strip 一个列表...
  • @tobias_k 是的,你是对的,实际上我在帖子中犯了错误,但现在我已经更新了帖子
  • @nekomatic 我只想写一段高效的代码(在这篇文章的顶部)
  • 在时间、内存或其他方面有效率吗?我看不出四次读取文件的全部内容是多么有效。无论如何,如果您担心内存使用,那么我建议您先从文件中一次读取并丢弃一行(使用readline()),直到您到达“开始”标记,然后继续使用您的原始代码。

标签: python-2.7 file-io removing-whitespace


【解决方案1】:

你的代码的问题是文件对象f是一个迭代器,一旦你调用f.readlines()它就用完了,所以通过调用f.readlines()找到一行的索引再次 无法工作。此外,调用readlines() 完全 可以消除您只存储文件中感兴趣的部分的努力,因为readlines() 无论如何都会将整个文件读入内存。

相反,只需记住您是否已经看过起始行并将以下行添加到列表中,直到您看到结束行。

with open(filename) as f:
    started, lines = False, []
    for line in f:
        stripped = line.strip()
        if stripped == "end": break
        if started: lines.append(stripped)
        if stripped == "start": started = True

或者,您也可以使用itertools.takewhile 将所有行移到最后一行。

import itertools
with open(filename) as f:
    for line in f:
        if line.strip() == "start":
            lines = itertools.takewhile(lambda l: l.strip() != "end", f)
            lines = map(str.strip, lines)
            break

甚至更短,使用另一个takewhile 读取(并丢弃)起始行之前的行:

with open("test.txt") as f:
    list(itertools.takewhile(lambda l: l.strip() != "start", f))
    lines = itertools.takewhile(lambda l: l.strip() != "end", f)
    lines = map(str.strip, lines)

在所有情况下,lines 都保留了开始行和结束行之间的(剥离的)行,两者都是互斥的。

【讨论】:

  • 更新if start:if started: 在上面的帖子中你的第一个代码
  • @Patrick Whops,当您尝试改进条目小部件中的代码时会发生这种情况...已修复。
【解决方案2】:

Tobias 的第一个答案可以用continue 稍作修改...

with open(filename) as f:
    started, lines = False, []
    for line in f:
        stripped = line.strip()
        if stripped == "end": break
        if stripped == "start": 
            started = True
            continue
        if not started: continue

        # process line here no need to store it in a list ...

【讨论】:

    猜你喜欢
    • 2019-12-05
    • 1970-01-01
    • 1970-01-01
    • 2015-03-12
    • 2022-11-22
    • 2019-02-10
    • 2015-05-13
    • 2021-06-25
    • 2013-12-08
    相关资源
    最近更新 更多