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

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

推荐答案

操作系统.路径isfile方法只返回True(如果文件存在)或False(如果不存在).在调用os之前,使用if语句判断其结果.重命名.

Python相关问答推荐

如何将桌子刮成带有Se的筷子/要求/Beautiful Soup ?

计算相同形状的两个张量的SSE损失

Pythind 11无法弄清楚如何访问tuple元素

滚动和,句号来自Pandas列

根据在同一数据框中的查找向数据框添加值

如何从具有不同len的列表字典中创建摘要表?

更改键盘按钮进入'

Telethon加入私有频道

Streamlit应用程序中的Plotly条形图中未正确显示Y轴刻度

我的字符串搜索算法的平均时间复杂度和最坏时间复杂度是多少?

AES—256—CBC加密在Python和PHP中返回不同的结果,HELPPP

从旋转的DF查询非NaN值

Python—为什么我的代码返回一个TypeError

Polars Group by描述扩展

在极点中读取、扫描和接收有什么不同?

从嵌套极轴列的列表中删除元素

用fft计算指数复和代替求和来模拟衍射?

如何根据一定条件生成段id

查找查找表中存在的列值组合

Polars定制函数返回多列