簡體   English   中英

文件存在時 os.rename 不會引發 FileExistsError

[英]os.rename does not raise FileExistsError when file exists

我有一個file_rename機制,我想用一個簡單的try/except塊來改進它,該塊將檢查重命名的文件是否已經存在於目錄中。

我在我的目錄中准備了 2 個文件: data.txtold_data.txt Function 應該拋出一個異常,因為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 上運行時才能做出該假設os.rename() state 的 Python 文檔

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

將文件或目錄src重命名為dst 如果dst存在,在許多情況下操作將失敗並出現OSError子類:

在 Windows 上,如果dst存在,則始終會引發FileExistsError

在 Unix 上,... [i]f [ srcdst ] 都是文件,如果用戶有權限, dst it [sic] 將被靜默替換。

要解決此問題,請改用帶有.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))

os.path.isfile 方法只返回 True(如果文件存在)或 False(如果不存在)。 在調用 os.rename 之前使用 if 語句檢查其結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM