【问题标题】:Python 3.7 - How to check if file exists and renamePython 3.7 - 如何检查文件是否存在并重命名
【发布时间】:2021-03-16 18:46:45
【问题描述】:

我正在尝试弄清楚如何检查源文件夹中的文件是否存在于目标文件夹中,然后将文件复制到目标文件夹。

如果源文件夹中的文件存在于目标文件夹中,请将源文件夹中的文件重命名为“_1”或_i+1,然后将其复制到目标文件夹。

例如(不会是.txt,仅以此为例,文件本质上是动态的):

我想将 file.txt 从文件夹 a 复制到文件夹 b。

file.txt 已存在于文件夹 b a 中。如果我尝试将 file.txt 复制到文件夹 b,我会收到复制错误。

将 file.txt 重命名为 file_1.txt将 file_1.txt 复制到文件夹 b b。如果 file_1.txt 存在,则将其设为 file_2.txt

到目前为止,我所拥有的是:

for filename in files:
    filename_only = os.path.basename(filename)
    src = path + "\\" + filename
    failed_f = pathx + "\\Failed\\" + filename

# This is where I am lost, I am not sure how to declare the i and add _i + 1 into the code.
   if path.exists(file_path):
       numb = 1
       while True:
           new_path = "{0}_{2}{1}".format(*path.splitext(file_path) + (numb,))
           if path.exists(new_path):
               numb += 1
               shutil.copy(src, new_path)
           else:
               shutil.copy(src, new_path)
   shutil.copy(src, file_path)

非常感谢。

【问题讨论】:

    标签: python python-3.x copy file-rename shutil


    【解决方案1】:
    import os
    for filename in files:
        src = os.path.join(path, filename)
        i = 0
        while True:
            base = os.path.basename(src)
            name = base if i == 0 else "_{}".format(i).join(os.path.splitext(base))
            dst_path = os.path.join(dst, name)
            if not os.path.exists(dst_path):
                shutil.copy(src, dst_path)
                break
            i += 1
    

    【讨论】:

    • 嗨,谢谢。不过我有一个问题,你在哪里检查 src 文件夹中的文件是否在目标文件夹中?
    • 在第一次循环迭代中,dst_path 等于 os.path.join(dst, os.path.basename(src))。它仅在 not os.path.exists(dst_path) 时复制,否则它会尝试将数字添加到文件名
    • 非常感谢(只是想学习语法)...这应该是最后一个问题,您有 `dst_path = os.path.join(dst, name)' ... “dst”代表什么?目标文件夹,在我上面的代码中是“failed_f”..?
    猜你喜欢
    • 1970-01-01
    • 2012-04-18
    • 2013-08-14
    • 1970-01-01
    • 2012-11-07
    • 1970-01-01
    • 2018-02-15
    • 2013-12-02
    • 1970-01-01
    相关资源
    最近更新 更多