[Python-ideas] Rewriting file - pythonic way

Alexey Shrub ashrub at yandex.ru
Sun Apr 15 04:57:00 EDT 2018


Hi all,

I am new in python (i am moving from Perl world), but I always love 
Python for hight level, beatuful and clean syntax.
Now I have question/idea about working with files.
On mine opinion it very popular use case:
1. Open file (for read and write)
2. Read data from file
3. Modify data.
4. Rewrite file by modified data.

But now it is looks not so pythonic:

with open(filename, 'r+') as file:
    data = file.read()
    data = data.replace('old', 'new')
    file.seek(0)
    file.write(data)
    file.truncate()

or something like this

with open(filename) as file:
    data = file.read()
data = data.replace('old', 'new')
with open(filename) as file:
    file.write(data)

I think best way is something like this

with open(filename, 'r+') as file:
    data = file.read()
    data = data.replace('old', 'new')
    file.rewrite(data)

but for this io.BufferedIOBase must contain rewrite method

what you think about this?





More information about the Python-ideas mailing list