Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open file, read it, process, and write back - shortest method in Python

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 ?

like image 664
Eli Bendersky Avatar asked Oct 22 '08 20:10

Eli Bendersky


People also ask

How do you open a file in read and write mode in Python?

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'.

What are the read & write file operation in Python?

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.

What is the correct way of opening a file for reading in Python?

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.


2 Answers

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),
like image 167
Hortitude Avatar answered Sep 21 '22 16:09

Hortitude


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.

like image 30
Robert Rossney Avatar answered Sep 19 '22 16:09

Robert Rossney