从python中的文件中删除记录

时间:2014-11-06 19:03:40

标签: python file

我有一个包含100个条目的文件。

如果文件中的记录与用户提供的输入相符,我想从文件中删除该记录内容。

我怎么能在python中做到这一点?

1 个答案:

答案 0 :(得分:1)

with open(your_f) as f:
    lines = f.readlines()
    for ind, line in enumerate(lines): 
        if your condition: # if line contains a match 
            lines[ind] ="" # set line to empty string
    with open(your_f,"w") as f: # reopen with w to overwrite
        f.writelines(lines) # write updated lines

例如,从以55开头的txt文件中删除一行:

with open("in.txt") as f:
    lines = f.readlines()
    for ind, line in enumerate(lines):
        if line.startswith("55"):
            lines[ind] = ""
    with open("in.txt","w") as f:
        f.writelines(lines)

输入:

foo
bar
55 foobar
44 foo

输出:

foo
bar
44 foo