I want to do some basic filtering on a file. Read it, do processing, write it back.
I'm not looking for "golfing", but want the simplest and most elegant method to achieve this. I came up with:
from __future__ import with_statement
filename = "..." # or sys.argv...
with open(filename) as f:
new_txt = # ...some translation of f.read()
open(filename, 'w').write(new_txt)
The with
statement makes things shorter since I don't have to explicitly open and close the file.
Any other ideas ?
Also if you open Python tutorial about reading and writing files you will find that: 'r+' opens the file for both reading and writing. On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'.
readlines() : This function returns a list where each element is single line of that file. readlines() : This function returns a list where each element is single line of that file. write() : This function writes a fixed sequence of characters to a file. writelines() : This function writes a list of string.
Reading Files in Python To read a file in Python, we must open the file in reading r mode. There are various methods available for this purpose. We can use the read(size) method to read in the size number of data. If the size parameter is not specified, it reads and returns up to the end of the file.
Actually an easier way using fileinput is to use the inplace parameter:
import fileinput
for line in fileinput.input (filenameToProcess, inplace=1):
process (line)
If you use the inplace parameter it will redirect stdout to your file, so that if you do a print it will write back to your file.
This example adds line numbers to your file:
import fileinput
for line in fileinput.input ("b.txt",inplace=1):
print "%d: %s" % (fileinput.lineno(),line),
I would go for elegance a different way: implement your file-reading and filtering operations as generators, You'll write more lines of code, but it will be more flexible, maintainable, and performant code.
See David M. Beazley's Generator Tricks for Systems Programmers, which is a really important thing for anyone who's writing this kind of code to read.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With