Python 2.7 删除外部文本文件中的行

Python 2.7 删除外部文本文件中的行,python-2.7,Python 2.7,您好,请问我如何迭代外部文件中的行,识别在每行的最后一个索引处具有0的行,并在检索未删除的行时删除这些行。即 input.txt = 1001 1001 0 1001 1002 0 1001 1003 0.058529 ... ... ... 9007 9007 0.0789 我试过这个 with open('input.txt', 'r') as

您好,请问我如何迭代外部文件中的行,识别在每行的最后一个索引处具有0的行,并在检索未删除的行时删除这些行。即

input.txt = 1001 1001 0 
            1001 1002 0 
            1001 1003 0.058529
            ...
            ...
            ...
            9007 9007 0.0789
我试过这个

with open('input.txt', 'r') as handle:
    for line in handle:
    o_d = line.split()
    if o_d[-1] == '0':
        o_d.pop()
        print o_d
我知道这只会在每一行中删除带有零的0,但是我需要帮助删除出现0的整行,然后用不带零的行写回文件


谢谢

这与您的代码非常接近。唯一的问题是您需要调用
str.strip
,因为
readlines
包含尾随的换行符

这段代码不是试图就地修改文件,而是先读入所有数据,然后写入以“0”结尾的所有行

# Read in the source data
with open('input.txt', 'r') as handle:
    lines = handle.readlines()
# Open the output file
with open('input.txt', 'w') as handle:
    # Examine each line of the source data
    for line in lines:
        # If it doesn't end with a '0', write it
        if line.strip()[-1] != '0':
            handle.write(line)
按照您的要求格式化最后一行的一种方法是将该行拆分为单独的值,将它们放入元组,然后将它们插入格式字符串,然后写入。例如:

"[(%s,%s,{%s})]" % tuple(line.split())
所以完整的代码是

# Read in the source data
with open('input.txt', 'r') as handle:
    lines = handle.readlines()
# Open the output file
with open('input.txt', 'w') as handle:
    # Examine each line of the source data
    for line in lines:
        # If it doesn't end with a '0', write it
        if line.strip()[-1] != '0':
            line.split()
            handle.write("[(%s,%s,{%s})]" % tuple(line.split()))

请在代码中至少提供一些解释,以供将来参考/澄清。@Moshe它运行良好。请你帮我把最后一行写下来。如果我需要格式化输出,使其看起来像这样[(100110001,{0.058529})],那该怎么做呢。谢谢