【问题标题】:Rename files within a folder - Python重命名文件夹中的文件 - Python
【发布时间】:2021-03-31 23:00:32
【问题描述】:

如何在不知道原始名称的情况下重命名文件夹中的文件?例如,我有一个 file.jpg,但不知道它叫什么,我想将其命名为 test.jpg,它包含一个文件夹中的所有文件。

【问题讨论】:

  • 使用 os.listdir(src_dir) 获取所有文件的列表,然后使用 os.rename() 重命名
  • 您不能将所有文件重命名为相同的名称。请改写您的问题,因为这对我来说没有多大意义。

标签: python file directory


【解决方案1】:

试试这个:

import os
import glob
# Getting all files in a folder (including hidden files)
files = os.listdir(os.path.expanduser("~/Downloads"))

# Getting all .jpg files in a directory
jpeg_files = glob.glob(os.path.expanduser("~/Downloads/*.jpeg"))

print(jpeg_files)
os.rename(jpeg_files[0], os.path.expanduser("~/Downloads/test.jpeg"))

如果要重命名所有 .jpeg 文件,请将最后一行替换为:

for file in jpeg_files:
    os.rename(file, os.path.expanduser("~/Downloads/test.jpeg"))

现在我使用os.expanduser() 只是为了让人们更容易测试

【讨论】:

    猜你喜欢
    • 2019-02-05
    • 1970-01-01
    • 2018-05-28
    • 1970-01-01
    • 1970-01-01
    • 2019-02-28
    • 1970-01-01
    • 2016-08-25
    • 2022-11-13
    相关资源
    最近更新 更多