Python: 将文件名改为列表中的人名

Python: Change file names to the names of people in a list

我有几张幻灯片,每张幻灯片对应一个人。我需要在它引用的个人名称之后命名每个文件 (.pptx)。我在大量重命名中看到的很多示例都将重命名变成顺序的,例如:

file1
file2
file3

我需要:

bob.pptx
sue.pptx
jack.pptx

我可以使用在此站点 https://www.marsja.se/rename-files-in-python-a-guide-with-examples-using-os-rename/:

上找到的 os 更改名称
import os, fnmatch
file_path = 'C:\Users\Documents\Files_To_Rename\Many_Files\'
files_to_rename = fnmatch.filter(os.listdir(file_path), '*.pptx')
print(files_to_rename)
new_name = 'Datafile'

for i, file_name in enumerate(files_to_rename):
    new_file_name = new_name + str(i) + '.pptx'
    
    os.rename(file_path + file_name, 
          file_path + new_file_name)

但是,这只是命名:

Datafile1
Datafile2
etc

我的例子

import os from pathlib
import Path
files = os.listdir("c:\tmp\")
for key in range(0, len(files)):
  print (files[key])
  os.rename("c:\tmp\" + files[key], "c:\tmp\" + files[key].replace("-",""))
  Path("c:\tmp\" + files[key] + '.ok').touch() # if u need add some extension

这就是我 运行 你的代码(避免我没有的文件路径!),让它打印输出而不仅仅是重命名

import os, fnmatch
file_path = '.\'
files_to_rename = fnmatch.filter(os.listdir(file_path), '*.pptx')
print(files_to_rename)
new_name = 'Datafile'

for i, file_name in enumerate(files_to_rename):
    new_file_name = new_name + str(i) + '.pptx'

    print (file_path + new_file_name)

    os.rename(file_path + file_name, 
              file_path + new_file_name)

这给了我

.\Datafile0.pptx
.\Datafile1.pptx
...

并确实给了我该文件夹中 pptx 文件的正确顺序。

所以我怀疑问题是您正在 获取您想要的文件名,但您在Windows 中看不到它们。解决方案:在 Windows 中显示文件类型。这是关于操作方法的许多可用链接之一:https://www.thewindowsclub.com/show-file-extensions-in-windows

谢谢大家的建议,我好像是在朋友的帮助下找到的:

import os, fnmatch
import pandas as pd
file_path = 'C:\Users\Documents\FolderwithFiles\'
files_to_rename = fnmatch.filter(os.listdir(file_path), '*.pptx') #looks for any .ppt in path, can make any ext

df = pd.read_excel('Names.xlsx') #make a list of names in an xl, this won't read the header, header should be Names, then list your names)

for i, file_name in zip(df['Names'], files_to_rename): #zip instead of a nest for loop
    new_file_name = i + '.pptx'
    os.rename(file_path + file_name, file_path + new_file_name)
    print(new_file_name)