开发者

How to remove line from the file in python [duplicate]

This question already has answers here: Closed 10 years ago.

Possible Duplicate:

Deleting a specific line in a file (python开发者_C百科)

I need to delete the line contains number '2' from the file f=

2 3
5 6
7 2
4 5


When you want to edit a file, you make a new file with the correct data and then rename the new file as the old file. This is what serious programs like your text editor probably do. (Some text editors actually do even weirder stuff, but there's no use going into that.) This is because in many filesystems the rename can be atomic, so that under no circumstances will you end up with the original file being corrupted.

This would lead to code to the effect of

with open(orig_file) as f, open(working_file, "w") as working: 
    # ^^^ 2.7+ form, 2.5+ use contextlib.nested
    for line in f:
        if '2' not in line: # Is this exactly the criterion you want?
                            # What if a line was "12 5"?
            working.write(line)

os.rename(working_file, orig_file)

You may want to use orig_file + '~' or the tempfile module for generating the working file.


with open('f', 'r+') as f:
  data = ''.join(filter(lambda l: '2' not in l.strip().split(' '), f))
  f.seek(0)
  f.truncate(0)
  f.write(data)


import fileinput
for line in fileinput.input('f',inplace =1):
  line = line.strip()
  if not '2' in line:
    print line 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜