[Python-ideas] Rewriting file - pythonic way

Serhiy Storchaka storchaka at gmail.com
Sun Apr 15 05:40:57 EDT 2018


15.04.18 11:57, Alexey Shrub пише:
> 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()

What do you mean by calling this not pythonic?

> 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

If the problem is that you want to use a single line instead of three 
line, you can add a function:

def file_rewrite(file, data):
      file.seek(0)
      file.write(data)
      file.truncate()

and use it. This looks pretty pythonic to me.



More information about the Python-ideas mailing list