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.

Recommended Answers

All 4 Replies

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)

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>
okfilename("HW2-data.dat")
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?

Nevermind, fixed it! Thank you very much :cool:

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.