0

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 if text.new.txt already exists,

  • text.new.3.txt if text.new.txt and text.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.

1 Answers1

1

If you want to keep your code and your format is filename.new.index.txt, when you check that filename.new.2.txt exists you can check the last file with glob:

from glob import glob

# path contains path
filelist = glob(path + "\\filename.new.*")
last_index = max([filename.split(".")[-2] for filename in filelist])

And assign last_index+1 as index for the new file.

For a more robust approach, consider applying str.zfill() to indices in order to sort them easily (i.e. 001, 002, 003...).

frab
  • 1,162
  • 1
  • 4
  • 14