Advertisement
Guest User

Untitled

a guest
Feb 28th, 2017
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.96 KB | None | 0 0
  1. import fileinput
  2. import os
  3.  
  4. with fileinput.FileInput(filename, inplace=True, backup='.bak') as file:
  5. for i, line in enumerate(file, start=1):
  6. if i & 1: # odd
  7. print(line, end='') # keep line (stdout is redirected to the file)
  8. os.unlink(filename + '.bak') # remove the backup on success
  9.  
  10. import sys
  11. from itertools import islice
  12.  
  13. sys.stdout.writelines(islice(file, 0, None, 2)) # keep lines[::2]
  14.  
  15. with open(filename) as file:
  16. lines = file.readlines()[::2] # lines to keep
  17. with open(filename, 'w') as file:
  18. file.writelines(lines)
  19.  
  20. from itertools import islice
  21.  
  22. with open(filename, 'r+') as file:
  23. write_offset = file.tell() # where to write next
  24. for line in islice(iter(file.readline, ''), 0, None, 2): # keep lines[::2]
  25. read_offset = file.tell() # where to read next
  26. file.seek(write_offset)
  27. file.write(line)
  28. write_offset = file.tell()
  29. file.seek(read_offset)
  30. file.truncate(write_offset)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement