I have a file_rename mechanism which I want to improve with a simple try/except block that will check if the renamed file does already exists in the directory.
I prepared in my directory 2 files: data.txt and old_data.txt. Function should throw an exception, as old_data.txt already exists, which implies that data was processed in the past.
However, the below code is not working, as it is still renaming the data.txt file. I'd appreciate any assistance and guidance on this.
@staticmethod
def file_rename(file, dir):
source_file_new_name = "old_" + file
try:
os.path.isfile(dir + source_file_new_name)
os.rename(os.path.join(dir, file), os.path.join(dir, source_file_new_name))
except FileExistsError:
raise FileExistsError("this file was already processed")
With Rafał's and BrokenBenchmark hint I came up with below version but not sure if its enough pythonic ;)
class FileExistsError(Exception):
pass
@staticmethod
def file_rename(file, dir):
source_file_new_name = "old_" + file
if os.path.isfile(dir + source_file_new_name):
raise FileExistsError("this file was already processed!")
else:
os.rename(os.path.join(dir, file), os.path.join(dir, source_file_new_name))