在.txt文件中查找变量的第一个实例,并删除它所在的行

时间:2016-03-22 12:35:53

标签: python python-3.x file-io

我创建了一个包含不同名称的文本文件,后跟一个格式为的数字:

Name 1, 10
Name 2, 5
Name 3, 5
Name 2, 7
Name 2, 6
Name 4, 8
ect.

我想找到变量'Name 2'首先出现的行 - 所以第2行,然后删除该行。这可能吗?

1 个答案:

答案 0 :(得分:1)

def skip_line_with(it, name):
    # Yield lines until find the line with `name`
    for line in it:
        if line.startswith(name):
            break  # Do not yield the line => skip the line
        yield line

    # Yield lines after the line
    for line in it:
        yield line

with open('a.txt') as fin, open('b.txt', 'w') as fout:
    fout.writelines(skip_line_with(fin, 'Name 2,'))

将创建没有不需要的行的新文件b.txt

更新如果您想要就地替换文件(假设文件不是很大):

def skip_line_with(it, name):
    for line in it:
        if line.startswith(name):
            break
        yield line
    for line in it:
        yield line

with open('a.txt', 'r+') as f:
    replaced = list(skip_line_with(f, 'Name 2,'))
    f.seek(0)
    f.writelines(replaced)
    f.truncate()