我有一个file_rename
机制,我想用一个简单的try/except
块来改进,它将判断重命名的文件是否已经存在于目录中.
我在我的目录中准备了两个文件:data.txt
和old_data.txt
.函数应该抛出一个异常,因为old_data.txt
已经存在,这意味着数据是在过go 处理的.
但是,下面的代码不起作用,因为它仍在重命名data.txt
文件.我非常感谢在这方面的任何帮助和指导.
@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")
根据拉法和布罗肯贝克的暗示,我想出了下面的版本,但不确定它是否足够通灵;)
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))