在python中的单独文件夹中重命名一组文件

发布于 2024-10-10 00:31:42 字数 351 浏览 0 评论 0原文

大家好,在 python 中重命名单独文件夹中的一组文件时遇到问题。我有一个文件夹结构,就像

images/p_0/aaa.jpg,bbb.jpg
images/p_1/aaa.jpg,bbb.jpg
images/p_2/aaa.jpg,bbb.jpg

我需要将这些 jpg 重命名为喜欢的

images/p_0/A-1.jpg,B-1.jpg
images/p_1/A-2.jpg,B-2.jpg
images/p_2/A-3.jpg,B-3.jpg

,并且我正在使用 os.rename 方法。我只是不知道如何循环浏览文件夹并找到图像并重命名它。

Hi guys have a problem with renaming a set of files in separate folder in python. i have a folder structure like

images/p_0/aaa.jpg,bbb.jpg
images/p_1/aaa.jpg,bbb.jpg
images/p_2/aaa.jpg,bbb.jpg

I need to rename these jpg to like

images/p_0/A-1.jpg,B-1.jpg
images/p_1/A-2.jpg,B-2.jpg
images/p_2/A-3.jpg,B-3.jpg

and i am using the os.rename method. I just don't get how to cycle through the folders and find the image and rename it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

不打扰别人 2024-10-17 00:31:42

使用 os.walk 和 os.rename。

import os
for root, dirs, files in os.walk(top, topdown=False):
    for name in files:
        #Rename your files and use os.path.join(root, name)

Use os.walk and os.rename.

import os
for root, dirs, files in os.walk(top, topdown=False):
    for name in files:
        #Rename your files and use os.path.join(root, name)
谜兔 2024-10-17 00:31:42

您可以使用 os.listdir() 来获取某个目录中的所有文件。您可能还想查看 os 模块 文档的其余部分。

You can use os.listdir() to get all the files in some directory. You might also want to look through the rest of the os module documentation.

你的心境我的脸 2024-10-17 00:31:42

查看 os.listdiros.walk,如果您有嵌套目录结构。

#!/usr/bin/env python

import os

# list all files
for filename in os.listdir('.'):
    print filename # do something with filename ...

def is_image(filename):
    """ Tiny filter function. """
    return filename.endswith(".jpg") or filename.endswith(".png")

# only consider files, which pass the `is_image` filter
for filename in filter(is_image, os.listdir('.')):
    print filename # do something with filename ...

Take a look at os.listdir or os.walk, if you have a nested directory structure.

#!/usr/bin/env python

import os

# list all files
for filename in os.listdir('.'):
    print filename # do something with filename ...

def is_image(filename):
    """ Tiny filter function. """
    return filename.endswith(".jpg") or filename.endswith(".png")

# only consider files, which pass the `is_image` filter
for filename in filter(is_image, os.listdir('.')):
    print filename # do something with filename ...
锦欢 2024-10-17 00:31:42

除了 os.walk() 之外,glob.glob() 可能也有用。

In addition to os.walk(), glob.glob() might be useful.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文