Python example to save file with same name like `somefile(n).txt` My little Python scriptie needs to save a file to the CWD, but sometimes the file already exists.

I found this short and clever example to string concatenate a time signature to the name here on SE. But I wanted to make the file name look pretty,

import os
import fnmatch
import re

somefiles = []
myfiles = []
root = "./"
onefn = False

for item in os.listdir(root):
    if os.path.isfile(os.path.join(root,item)):
        somefiles.append(item)

for fname in somefiles:
    if fnmatch.fnmatch(fname, 'somefile(*).txt'):
        myfiles.append(fname)
    elif fname == 'somefile.txt':
        onefn = True     

if len(myfiles) &gt; 0:
    maxnum = re.search(r'\(([0-9]+)\)', max(myfiles))
    with open('somefile(%s).txt' % (str(int(maxnum.group(1)) + 1),), 'w') as f:
        f.write("This is some text in a new file.")
elif onefn:
    with open('somefile(1).txt', 'w') as f:
        f.write("This is sommore text in a new file.")
else:              
    with open('somefile.txt', 'w') as f:
        f.write("This is enuf text in a new file.")


This is a beast, but it will write somefile(n).txt.
Any recommendations to make it less beastly?
One aspect I'd like to mention is sorting:

The contain does a max(myfiles), which is on the filenames.

In particular, out of "somefile(9).txt" and "somefile(10).txt", the max will be "somefile(9).txt". It will then choose "somefile(10).txt" as the new filename, overwriting its original content.

This is because 9 is larger than 1.