用python以特定形式重命名文件

2024-04-27 00:18:23 发布

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

我正在尝试重命名一个文件夹中的文件,模式为0001、0002、0010、0100等等。我对python非常陌生,所以很抱歉问了这么基本的问题。你知道吗

我到处搜索过,遇到的大多数代码都会重命名文件(不是我想要的方式)或去掉某些字符。我还遇到了使用额外模块(glob)的代码,这只会让我更进一步。我看到的大部分东西只是让我头晕目眩;目前我的技能并没有超出简单的函数,if、when、for、while语句等等。你知道吗

我已经拼凑了一些代码,我(有些)理解,但它不工作。你知道吗

import os

dir = os.listdir("D:\\temp\\Wallpapers")

i = 0

for item in dir:
    dst ="000" + str(i) + ".jpg"
    src = item
    dst = item + dst 

    # rename() function will 
    # rename all the files 
    os.rename(src, dst) 
    i += 1

这是我得到的错误:

Traceback (most recent call last):
  File "rename.py", line 14, in <module>
    os.rename(src, dst)
FileNotFoundError: [WinError 2] The system cannot find the file specified: '00-Pyatna.jpg' -> '0000.jpg'

Tags: 文件the代码insrc文件夹foros
2条回答

首先,您可以使用以下功能检索文件夹中已存在的最大数字

import re
def max_counter_in_files(folder):
    files = os.listdir(folder)
    maxnum = '0'
    if files:
        maxnum = max([max(re.findall("[\d]+", file)) for file in files])
    return maxnum

例如,如果您的文件夹包含

file001.txt
file002.txt
file003.txt

然后max_counter_in_files('path/to/your/files')将返回3。你知道吗

其次,在添加新文件时,可以使用该函数增加下一个文件名。例如

counter = int(self.max_counter_in_files(dest_path))
filename = f"filename{counter+1:04d}.txt"

filename就是"filename0004.txt"。你知道吗

它不起作用,因为您可能不在正确的目录中,并且您正在尝试在当前所在的目录中查找这些文件。你应该使用绝对路径。请参见以下代码

import os

base_path = "D:/temp/Wallpapers"
files = os.listdir(base_path)


for i, fp in enumerate(files):
    dst = os.path.join(base_path, "{0:04d}.jpg".format(i))
    src = os.path.join(base_path, fp) 
    os.rename(src, dst) 

相关问题 更多 >