如何使用python更改文件扩展名

时间:2019-04-25 06:07:22

标签: python-3.x

在一个文件夹中,我有100个文件的扩展名为“ .txt”,“。doc”,“。pdf”。我需要将文件重命名为:

  1. 如果文件名以“ .txt”结尾->替换文件名以“ .jpg”
  2. 如果文件名以“ .doc”结尾->替换文件名以“ .mp3”结尾
  3. 如果文件名以“ .pdf”结尾->替换文件名以“ .mp4”结尾

到目前为止,我已经尝试过这个

import os,sys

folder ="C:/Users/TestFolder"
for filename in os.listdir(folder):
    base_file, ext = os.path.splitext(filename)
    print(ext)
    if ext == '.txt':
        print("------")
        print(filename)
        print(base_file)
        print(ext)
        os.rename(filename, base_file + '.jpg')

    elif ext == '.doc':
        print("------")
        os.rename(filename, base_file + '.mp3')

    elif ext == '.pdf':
        print("------")
        os.rename(filename, base_file + '.mp4')
    else:
        print("Not found")

1 个答案:

答案 0 :(得分:0)

首先,您可以将映射存储在字典中,然后在遍历文件夹时找到扩展名,只需使用映射来创建新文件名并保存。

import os

folder ="C:/Users/TestFolder"

#Dictionary for extension mappings 
rename_dict = {'txt': 'jpg', 'doc': 'mp3', 'pdf': 'mp4'}
for filename in os.listdir(folder):

    #Get the extension and remove . from it
    base_file, ext = os.path.splitext(filename)
    ext = ext.replace('.','')

    #If you find the extension to rename
    if ext in rename_dict:
        #Create the new file name
        new_ext = rename_dict[ext]
        new_file = base_file + '.' + new_ext

        #Create the full old and new path
        old_path = os.path.join(folder, filename)
        new_path = os.path.join(folder, new_file)

        #Rename the file
        os.rename(old_path, new_path)