So I need to write a function that if a file exists, it will change the file name by sequentially adding integers, starting with 1, to the base file name (the part that does not include the file extension). so if the filename is hello.dat, then it will return hello1.dat and if it exists, then hello2.dat, and so on. If it does not exist it'll stop.

I understand that I have to use a while loop and os.path.isfile. My teacher suggested rsplit and I don't understand it. I've googled it, and read many sites, and it's so unclear to me! it says something about sep, maxsplit, delimiter? I don't understand.

Edited by KickAssElmo: n/a

5 Years
Discussion Span
Last Post by ihatehippies

So you have to create a unique file name with incremental values starting at 1. First thing you gotta do it separate the file from the folder. os.path is going to be your friend for this one

from os import path
# get the absolute path
file_path = path.abspath(file_path)
# splits the filename from the folder
folder, filename = path.split(file_path)

then you have to separate the file name from its extension

name, ext = path.splitext(filename)

then you have to start your loop that checks for a file's existance

n = 0
while exists(file_path):
   n += 1
   file_path = '%s(%s)%s' % (path.join(folder, name), n, ext)
return path.abspath(file_path)

Edited by ihatehippies: n/a


Ok, so the split was for separating the file from the folder and separating the filename from its extension. Thanks for clearing that up :)
I have a question though,
when I didn't separate the file from its folder I got:

>>> okfilename("HW2-data.dat")
'C:\\Users\\Golden Hands\\Documents\\HW2-data(1).dat'

which makes sense, but when I inputed the code that you wrote for separating it I got:

>>> okfilename("HW2-data.dat")

Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
File "C:\Users\Golden Hands\Documents\assignment 2.py", line 19, in okfilename
file_path = path.abspath(file_path)
UnboundLocalError: local variable 'file_path' referenced before assignment
how can this be fixed?

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.