gpt4 book ai didi

python - 文件存在时,os.rename 不会引发 FileExistsError

转载 作者:行者123 更新时间:2023-12-05 01:04:46 29 4
gpt4 key购买 nike

我有一个 file_rename 机制,我想用一个简单的 try/except block 来改进它,该 block 将检查重命名的文件是否已经存在于目录中。

我在我的目录中准备了 2 个文件:data.txtold_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))

最佳答案

您的代码假定 os.rename 将引发 FileExistsError只有在代码在 Windows 上运行时才能做出这种假设。 The Python docs for os.rename() state :

os.rename(src, dst, *, src_dir_fd=None, dst_dir_fd=None)

Rename the file or directory src to dst. If dst exists, the operation will fail with an OSError subclass in a number of cases:

On Windows, if dst exists a FileExistsError is always raised.

On Unix, ... [i]f both [src and dst] are files, dst it [sic] will be replaced silently if the user has permission.

要解决此问题,请使用带有 .isfile()if 语句,而不是依赖于铰链的 try/except关于不可移植的行为:

def file_rename(file, dir):
source_file_new_name = "old_" + file
if os.path.isfile(os.path.isfile(dir + source_file_new_name)):
os.rename(os.path.join(dir, file), os.path.join(dir, source_file_new_name))

关于python - 文件存在时,os.rename 不会引发 FileExistsError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71542569/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com