Suppose that I have a textfile text.txt
. In Python, I read it to lines
(which is a str
object), make some changes to lines
, and after that I want to save lines
to a new file in the same directory. The new filename should be
text.new.txt
if it doesn't exist already,text.new.2.txt
iftext.new.txt
already exists,text.new.3.txt
iftext.new.txt
andtext.new.2.txt
already exist,
etc.
I came up with the following solution:
import itertools
import os
file_1 = r'C:\Documents\text.txt'
with open(file_1, mode='r', encoding='utf8') as f:
lines = f.read()
# Here I modify `lines`
# ...
postfix = '.new'
root, ext = os.path.splitext(file_1)
file_2 = f'{root}{postfix}{ext}'
if os.path.isfile(file_2):
for j in itertools.count(start=2):
file_2 = f'{root}{postfix}.{j}{ext}'
if not os.path.isfile(file_2):
break
with open(file_2, mode='w', encoding='utf8') as f:
f.write(lines)
I realize that I can use while True ... break
instead of itertools.count()
but it is essentially the same thing. I am wondering if there are any substantially better solutions to this problem.