【问题标题】:Renaming all files in a folder with specific extension using python使用python重命名具有特定扩展名的文件夹中的所有文件
【发布时间】:2021-10-08 15:50:22
【问题描述】:

我正在使用 python,而且我非常新。我有一个包含数百个文件的文件夹,我已将它们的扩展名重命名为 jp、gi、jpe 和 mp。所以,我想遍历所有这些,根据它们的扩展名重命名它们。如果是 jp 则为 jpg,如果为 jpe 则为 jpeg,gif 为 gi,mp4 为 mp。我知道这很多,但是,我们将不胜感激!谢谢!

【问题讨论】:

    标签: python operating-system rename


    【解决方案1】:

    jp 然后 jpg,如果是 jpe 然后 jpeg,gif 代表 gi,mp4 代表 mp

    你可以先这样创建一个字典:

    extensions={'jp':'jpg','jpe':'jpeg','gi':'gif','mp':'mp4'}
    

    然后导入os模块,并使用os.listdir(folder_path),后接os.rename()

    import os
    folder_path='/.../.../folder'
    extensions={'jp':'jpg','jpe':'jpeg','gi':'gif','mp':'mp4'}
    for i in os.listdir(folder_path):
        paths=i.split('.') #==== Split the string based on the parameter
     
        if extensions.get(paths[-1])!=None: #=== If a key is not present, it returns None. So if there is another file named .docx or .txt or a folder, it will return None.
           os.rename(os.path.join(folder_path,i),os.path.join(folder_path,paths[0]+"."+extensions.get(paths[-1]))) #====os.path.join(folder_path,i) joins the folder path and file name
    

    【讨论】:

    • 谢谢,我没有真正得到代码 :( 但我想它会起作用的,所以干杯!
    • 嘿 @Sujay - FWIW,this 这就是为什么我建议不要投票关闭垃圾邮件,而只是标记。但是很抱歉,我给人的印象是(我确信我确实做到了,我的措辞很糟糕)我认为你没有标记以及。 :-) 希望我的问题的答案是“不,对系统没有影响”。有社会工程方面,但对我来说它很薄弱,不适合发表评论。只是想我会解释一下。 :-)
    【解决方案2】:

    您需要从所有“损坏”文件所在的目录启动此文件。不客气。

    import os
    from os import listdir
    from os.path import isfile, join
    
    # Get path to current dir
    cwd = os.getcwd()
    
    # Get all files in dir
    onlyfiles = [f for f in listdir(cwd) if isfile(join(cwd, f))]
    
    
    for file in onlyfiles:
    
        # Get the current format
        s = file.split(".")
        br = s[-1]
    
        if br == 'jp':
            new = 'jpg'
        elif br == 'gi':
            new = 'gif'
        elif br =='jpe':
            new = 'jpeg'
        else:
            continue
    
        # Change format and get new filename
        s[-1] = new
        s = '.'.join(s)
    
        # Rename file
        os.rename(file, s)
        print(f"Renamed {file} to {s}")
    

    【讨论】:

    • 谢谢伙计,我不明白发生了什么,但我想它会起作用的,我会尽快尝试,谢谢!!
    【解决方案3】:

    首先在“旧”和“新”扩展之间进行字典映射。从我能读到的(因为你有很多文件)你可能有扩展的完整性问题......也许是jjp 扩展?所以映射步骤非常重要...... 其次,要重命名文件,请注意从文件系统中的哪个位置运行程序。这是一个基本的解决方案

    import os
    
    extensions = {'jp': 'jpg', 'jpg': 'jpeg', 'mp': 'mp4'}
    
    
    def rename_files(dir_path, extensions):
        files = os.listdir(dir_path)
    
        for file in files:
            for ext in extensions:  # loop over the old extensions
                if file.endswith(ext):  # check the extension
                    file_new = '{}.{}'.format(os.path.splitext(file)[0], extensions[ext])
                    os.rename(os.path.join(dir_path, file_new)) # rename the files
                    print('{} --> {}'.format(file, file_new))
    
    
    dir_of_the_files = '.'
    rename_files(dir_of_the_files, extensions)
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-13
      • 1970-01-01
      • 2015-06-07
      相关资源
      最近更新 更多