Python修改文件后缀名

    科技2022-08-25  106

    读万卷书,行万里路——木子成

    记事本练习html,解决来回修改后缀名

    程序运行后项目文件夹下生成exe文件,后续双击exe文件即可修改

    可修改当前运行所在文件及其子文件中所有html和txt文件循坏修改后缀名

    """ name = os.path.splitext():分离文件名(name[0])和后缀name[1] os.rename(new_filename, old_filename):修改文件名,若不在最初工作地址则需更改 os.listdir(文件地址):得到当前目录的所有文件以及文件夹(file) os.path.join(根文件地址, file):得到file的绝对地址 os.path.isdir(file的绝对地址):判断是否为文件夹(isfile判断是否为文件) os.chdir(根文件地址):修改根文件地址 os.getcwd():得到当前工作地址 """ import os def renaming(file): """修改后缀""" ext = os.path.splitext(file) # 将文件名路径与后缀名分开 if ext[1] == '.txt': # 文件名:ext[0] new_name = ext[0] + '.html' # 文件后缀:ext[1] os.rename(file, new_name) # tree()已切换工作地址,直接替换后缀 elif ext[1] == '.html': new_name = ext[0] + '.txt' os.rename(file, new_name) def tree(path): """递归函数""" files = os.listdir(path) # 获取当前目录的所有文件及文件夹 for file in files: file_path = os.path.join(path, file) # 获取该文件的绝对路径 if os.path.isdir(file_path): # 判断是否为文件夹 tree(file_path) # 开始递归 else: os.chdir(path) # 修改工作地址(相当于文件指针到指定文件目录地址) renaming(file) # 修改后缀 this_path = os.getcwd() # 获取当前工作文件的绝对路径(文件夹) tree(this_path)

     

    Processed: 0.028, SQL: 9