在执行自动化的脚本的时候,生成的文档或者保存的数据存在着没有定义具体的保存格式完成了保存。在打开文档的过程中,会存在着无法直接通过默认软件打开的问题。虽然选择应用来打开文件也不是一件难事,如果能够一键更改文件的后缀,会不会让自己心情更加愉悦一些呢?

import os
 
 
def Add_Suffix(path, suffix):
    files = os.listdir(file_path)
    for i, file in enumerate(files):
        old_name = os.path.join(file_path, file)
        new_name = os.path.join(file_path, file.split(".")[0] + suffix)
        os.rename(old_name, new_name)

file_path = r'C:\Users\Desktop\Log'
suffix = '.pcap'
Add_Suffix(file_path,suffix)

上面是最简单的直接添加文件格式的后缀。程序中沿用的路径是绝对路径,如果需要更改为相对路径,请大家自己发挥。

如果保存的文件格式不对,那么也可以一键更改所有的文件后缀。脚本如下:

import os
 
def name_split(file):
    suffix = os.path.splitext(file)    # 将路径下的文件名与后缀分开
    if suffix[1] == '.pcap':                    # 文件名存储在 suffix[0]
        new_name = suffix[0] + '.mp4'         # 文件后缀存储在 suffix[1]
        os.rename(file, new_name)
    elif suffix[1] == '.mp4':
        new_name = suffix[0] + '.pcap'
        os.rename(file, new_name)
 
 
def get_all_file(path):
    files = os.listdir(path)    
    for file in files:
        file_path = os.path.join(path, file)  
        if os.path.isdir(file_path):    
            get_all_file(file_path)    
        else:
            os.chdir(path)      
            name_split(file)      
 
 
target_path = r'C:\Users\youth-ping zhan\Desktop\ZHANPing_Log'
get_all_file(target_path)

Logo

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。

更多推荐