Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to modify lines in a file in-place?

Tags:

python

file-io

Is it possible to parse a file line by line, and edit a line in-place while going through the lines?

like image 589
Blankman Avatar asked Mar 27 '11 23:03

Blankman


People also ask

How do I put text in a specific position of a file in Python?

seek(count + cn) # place cursor at the correct character location remainder = f. read() # store all character afterwards f. seek(count + cn) # move cursor back to the correct character location f. write(text + remainder) # insert text and rewrite the remainder return # You're finished!


1 Answers

Is it possible to parse a file line by line, and edit a line in-place while going through the lines?

It can be simulated using a backup file as stdlib's fileinput module does.

Here's an example script that removes lines that do not satisfy some_condition from files given on the command line or stdin:

#!/usr/bin/env python # grep_some_condition.py import fileinput  for line in fileinput.input(inplace=True, backup='.bak'):     if some_condition(line):         print line, # this goes to the current file 

Example:

$ python grep_some_condition.py first_file.txt second_file.txt 

On completion first_file.txt and second_file.txt files will contain only lines that satisfy some_condition() predicate.

like image 78
jfs Avatar answered Sep 23 '22 10:09

jfs