我有一个file_rename
我想通过一个简单的改进机制try/except
块将检查重命名的文件是否已存在于目录中。
我在我的目录中准备了2个文件:data.txt
and old_data.txt
。函数应该抛出异常,如下所示old_data.txt
已经存在,这意味着数据在过去已被处理过。
但是,下面的代码不起作用,因为它仍在重命名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")
根据 Rafał 和 BrokenBenchmark 的提示,我想出了下面的版本,但不确定它是否足够 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))