【发布时间】:2021-05-26 11:12:24
【问题描述】:
我是编码新手。 是否可以使用通配符来重命名目录中的文件?
例如一个文件夹中有两个文件:
asdxyd01.pdf
cdc1pxych001.pdf
想要通过删除“xy”之前的所有字符来重命名文件。
我正在使用以下代码,它非常适合仅删除特定单词。
# Function to replace words in files names in a folder
import os
def main():
i = 0
# Ask user where the PDFs are
path = input('Folder path to PDFs: ')
# Sets the scripts working directory to the location of the PDFs
os.chdir(path)
filetype = input('entre file extention here: ')
rep = input('entre word to remove from file name: ')
for filename in os.listdir(path):
my_dest = filename.replace(rep, "") +"."+filetype
my_source = filename
my_dest = my_dest
# rename() function will
# rename all the files
os.rename(my_source, my_dest)
i += 1
# Driver Code
if __name__ == '__main__':
# Calling main() function
main()
【问题讨论】:
标签: python python-3.x wildcard