Reputation: 658
So I feel like I'm probably using the wrong words to look around for code for this on Google/StackOverflow.
I'm building a script that (among other things) is going to be doing a lot of moving files around.
I currently have a little line to split the filename from the extension, and to add Filename + (Duplicate)+Extension if the file already exists in the directory.
However, I feel like there HAS to be a simple little one-liner that will essentially do (Duplicate), (Duplicate 1), (Duplicate 2), (Duplicate 3), etc. (essentially just changing that second number to the next number if a file exists with the current one).
What's the simple solution I'm too stupid to be able to figure out myself?
Sorry, it hadn't occurred to me that my current code might help people answer my question!
def destination(self, f): return os.path.abspath('.')+'/'+self.filename(f)+'/'+self.filename(f)+' (Duplicate)'+self.extension(f) if and os.path.isfile(os.path.abspath('.')+'/'+self.filename(f)+'/'+f) else os.path.abspath('.')+'/'+self.filename(f)+'/'+f
I've used a slightly altered method of getting filename and extensions (essentially just to get around some rar parts and some folder issues). But 'self.filename(f) and self.extension(f) are basically just os.splittext(f)[0] and os.splittext(f)[1].
Upvotes: 2
Views: 2150
Reputation: 601401
Of course, there is some one-liner to do this, but I cannot think of a very readable one. I'd go for something like this:
def alternative_names(filename):
yield filename
base, ext = os.path.splitext(filename)
yield base + "(Duplicate)" + ext
for i in itertools.count(1):
yield base + "(Duplicate %i)" % i + ext
target_name = next(alt_name
for alt_name in alternative_names(target_name)
if not os.path.exists(alt_name))
(This might basically be what you did, but you didn't post your code.)
Upvotes: 5