为什么在使用此python脚本重命名文件时会删除这些文件?

2024-03-28 13:16:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了这个程序,使用以下代码将我所有的随机墙纸名称重命名为wallpaper1wallpaper2等等:

import os
path = os.chdir("/home/samipkarki/Pictures/Wallpapers")
value = 1
for file in os.listdir("path"):
    new_filename = f'wallpaper{value}.jpg'
    os.rename(file, new_filename)
    value += 1

但是每次我运行代码时,一半的文件被重命名,另一半被永久删除


Tags: path代码import程序名称墙纸newvalue
3条回答

这是一个有点依赖于平台的细节。如果您使用的是Windows,则会引发FileExistsError异常,但在Unix上不会

这就是文件中所说的:

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, if src is a file and dst is a directory or vice-versa, an IsADirectoryError or a NotADirectoryError will be raised respectively. If both are directories and dst is empty, dst will be silently replaced. If dst is a non-empty directory, an OSError is raised. If both are files, dst it will be replaced silently if the user has permission. The operation may fail on some Unix flavors if src and dst are on different filesystems. If successful, the renaming will be an atomic operation (this is a POSIX requirement).

因此,您需要手动检查文件是否存在,如果存在,则以某种方式进行处理

有一件事可能不会影响您的程序,那就是检查以下表格(来自alaniwi的答案):

while os.path.exists(new_filename):
    value += 1
    new_filename = f'wallpaper{value}.jpg'
os.rename(file, new_filename)

它并不完全安全。在确定文件名可用的事件和开始写入的事件之间,另一个进程可能会创建具有该名称的文件。如果这是一个问题,请看一下this question

将alaniwi的方法与此相结合,可以如下所示:

while True:
    value += 1
    new_filename = f'wallpaper{value}.jpg'

    try:
        os.open(new_filename, os.O_CREAT | os.O_EXCL)
        break
    except FileExistsError:
        pass

基本原则是,你永远无法事先知道手术是否成功。因此,您需要做的是尝试执行一个操作,看看是否成功

(此处建议一个相当小的改动,但作为回答,因为很难通过评论清楚地显示出来。)

如果新文件名存在,请插入一个检查,如果存在,则继续递增该数字,直到得到一个不存在的文件名。这将防止覆盖以前运行相同脚本时已重命名的文件

import os
path = os.chdir("/home/samipkarki/Pictures/Wallpapers")
value = 1
for file in os.listdir("path"):
    new_filename = f'wallpaper{value}.jpg'
    while os.path.exists(new_filename):
        value += 1
        new_filename = f'wallpaper{value}.jpg'
    os.rename(file, new_filename)
    value += 1

最好将重命名的文件保存到单独的文件夹中,您可以使用enumerate()作为编号:

import os
path = os.chdir("/home/samipkarki/Pictures/Wallpapers")
for n,file in enumerate(os.listdir("path")):
    new_filename = f'wallpaper{n+1}.jpg'
    os.rename(file, "/home/samipkarki/Pictures/Wallpapers2/"+new_filename) # Put it in another folder

确保在“图片”文件夹中创建了另一个名为“墙纸2”的文件夹

相关问题 更多 >