【发布时间】:2021-12-05 16:25:44
【问题描述】:
我是一名新手编码员。我需要实现上述目标,因为我正在使用大约 600 个随机名称下载的 pdf,并希望将它们更改为各自的标题。自过去几天以来,我一直在尝试解决此问题,但无处可去。我确实找到了一个不错的 4 年旧代码,它完全符合我的要求。但它似乎存在一些问题并且不适用于 Python 3.10。
【问题讨论】:
标签: python
我是一名新手编码员。我需要实现上述目标,因为我正在使用大约 600 个随机名称下载的 pdf,并希望将它们更改为各自的标题。自过去几天以来,我一直在尝试解决此问题,但无处可去。我确实找到了一个不错的 4 年旧代码,它完全符合我的要求。但它似乎存在一些问题并且不适用于 Python 3.10。
【问题讨论】:
标签: python
有很多不同的方法可以回答这个问题,但在我看来,最简单的方法是使用 Python 的模块 os。
要重命名许多文件,您需要做的第一件事是将所有 PDF 文件放在一个文件夹中。完成后,您可以使用以下代码:
def batchRenmePDF(folder, newName):
import os
suffix = 0
for each_pdf in os.listdir(folder):
suffix += 1
path = os.path.join(folder,each_pdf)
os.rename(path,f"{newName}_{suffix}.png")
这是上面代码的更深入版本:
def batchRenmePDF(folder, newName):
'''
A function to quickly rename PDFs
args:
folder (str, path): The path for the folder with all the PDFs
newName (str): The name for the new PDFs (Do not include filetypes)
'''
# Import required modules
import os
# Make sure the user's folder exists
if os.path.exists(folder):
pass
else:
print("Folder does not exist")
exit()
# If the user added the filetype in the newName, replace it with nothing
if str(newName).endswith(".pdf") or str(newName).endswith(".PDF"):
newName = str(newName).replace(".pdf","")
newName = str(newName).replace(".PDF","")
else:
pass
# Create the variable for the suffix for all the PDFs
suffix = 0
# Loop through all PDFs in the folder the user gave
for each_pdf in os.listdir(folder):
# Add 1 to the suffix so each time the PDF will have a different number
suffix += 1
# Create the path for the PDF using the folder path and the PDF name
path = os.path.join(folder,each_pdf)
# Actually renaming the PDFs
os.rename(path,f"{newName}_{suffix}.png")
【讨论】: