如何在包含特定文本的文件夹中搜索文件并在 Python 中重命名该文件

How to search for file in folder containing specific text and rename that file in Python

我正在尝试查找包含我使用列表传递的特定文本的文件名。我已经能够找到这些文件,但我似乎无法重命名它们。我不确定我做错了什么,所以任何帮助将不胜感激。 python 还很新,所以只是尝试通过一些简单的任务来学习。

from os import rename, listdir
import fnmatch

i = 0
divisions = ['BAT','FAB','HIN','OFA','SBY','VAL',
             'FRE','JEF','OLA','SPR','WEB','CTV',
             'MOB','PET','SWN','DEN','GRE','MTJ',
             'ROS','SXB','DWT','HAI','OAK','RPB','TUL']

divs = listdir('.')
ending = " Financials.xlsx"

for div in divs:
    if fnmatch.fnmatch(div, divisions[i]):
        rename(div, divisions[i] + ending)
    i += 1

您的代码有两个问题。首先,fnmatch 模式需要一个通配符来匹配文件名。其次,您只比较每个文件名的 1 divisions 个值,这时您需要遍历所有文件名直到找到匹配项。修复这些会给你以下结果(我重命名了几个值,因为当文件列表是“divs”时有一个叫做“divisions”的东西有点混乱)

from os import rename, listdir
from fnmatch import fnmatch

divisions = ['BAT','FAB','HIN','OFA','SBY','VAL',
             'FRE','JEF','OLA','SPR','WEB','CTV',
             'MOB','PET','SWN','DEN','GRE','MTJ',
             'ROS','SXB','DWT','HAI','OAK','RPB','TUL']

# build (division name, fnmatch pattern) for each division
patterns = [(division, f"{division} Financials*.xlsx") for division in divisions]

filenames = listdir('.')

for filename in filenames:
    for division, pattern in patterns:
        if fnmatch(filename, pattern):
            rename(filename, f"{division} Financials.xlsx")
            break

如果你想将其具体限制在 2020 年,模式将会改变。事实上,您根本不需要 fnmatch,因为您知道确切的文件名。

from os import rename, listdir

divisions = ['BAT','FAB','HIN','OFA','SBY','VAL',
             'FRE','JEF','OLA','SPR','WEB','CTV',
             'MOB','PET','SWN','DEN','GRE','MTJ',
             'ROS','SXB','DWT','HAI','OAK','RPB','TUL']
filename_map = dict(f"{division} Financials 2020.xlsx":f"{division} Finanacials.xlsx" 
    for division in divisions)

filenames = listdir('.')

for filename in filenames:
    mapped = filename_map.get(filename)
    if mapped:
        rename(filename, mapped)