1

Possible Duplicate:
Deleting a specific line in a file (python)

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

2 3
5 6
7 2
4 5
0

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

2
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)

15 Comments

data = ''.join(l in f if '2' not in l.split(' ')) ^ SyntaxError: invalid syntax
@ammar Refresh the page ;). But indeed, that version misses a for l in f: data = ''.join(l for l in f if '2' not in l.split(' ')).
data = ''.join(lambda l: '2' not in l.strip().split(' '), f) TypeError: join() takes exactly one argument (2 given)
@ammar I'm blaming the late hour here. Corrected, somehow I forgot the filter call when I copied it from my shell to stackoverflow. Sorry.
Note that this method allows the file to be corrupted due to unexpected termination.
|
-1
import fileinput
for line in fileinput.input('f',inplace =1):
  line = line.strip()
  if not '2' in line:
    print line 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.