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