成都网站优化师,产品推销文案,网站建设初期问题常见,武进区住房和城乡建设局网站1. 批量添加文件名后缀
#1----批量添加文件名后缀#xff08;.nc#xff09;。#指定wrfout文件所在的文件夹
path /mnt/wtest1/#列出路径path下所有的文件
file_names os.listdir(path) #遍历在path路径下所有以wrfout_d01开头的文件#xff0c;在os.path…1. 批量添加文件名后缀
#1----批量添加文件名后缀.nc。#指定wrfout文件所在的文件夹
path /mnt/wtest1/#列出路径path下所有的文件
file_names os.listdir(path) #遍历在path路径下所有以wrfout_d01开头的文件在os.path.basename()返回的一个代表指定路径基本名称的字符串值后加入“.nc”后缀再重命名文件。
for file in file_names:if file[0:10] ! wrfout_d01:continuebase_name os.path.basename(file)new_n base_name .ncos.rename(os.path.join(path, file), os.path.join(path, new_n))#建立空列表选取path文件路径下所有前缀名为wrfout_d01的nc文件填充该列表
list_names []
for ncfile in os.listdir(path):if ncfile[0:10] ! wrfout_d01: #通过索引选择想要的数据可以按照需要进行更改continuelist_names.append(ncfile)#将模拟结果文件名按照时间进行排序
list_names_sort np.sort(list_names)
2.批量删除文件名后缀
假如运行了两遍添加.nc后缀的代码生成了.nc.nc后缀命名的文件名如何批量删掉一组.nc后缀
# coding:utf-8
#删除文件名后缀
import os, shutilrootdir path # 原始带有后缀名的文件存放路径
remove_path /mnt/wtest1/removenc/ # 去除了后缀名的文件存放路径路径必须存在。# 修改文件名
def renameFile(oldname, newname):print(oldname:, oldname)print(newname:, newname)# os.rename(oldname, newname)shutil.copyfile(oldname, newname) #shutil.copyfile(src, dst):将名为src的文件的内容无元数据复制到名为dst的文件中 。# shutil.move(newname,remove_path) #shutil.move(src, dst):将名为src的文件夹中的内容无元数据递归移动到名为dst的文件夹中在此的作用同shutil.copyfile。# 列出文件
def listTxtFile(filepath):if os.path.isfile(filepath) and .nc or .nc.nc filepath[-6:]:#根据后缀名的长度设置.nc.nc为[-6:]。 oldName filepathnewName oldName[:-3] #根据所要保存的后缀名的长度设置renameFile(oldName, newName)shutil.move(newName, remove_path)# 遍历目录下所有的文件
def listPath(filepath):fileList os.listdir(filepath)for file in fileList:files os.path.join(filepath, file)if os.path.isdir(files):listPath(files)else:listTxtFile(files)if __name__ __main__:listPath(rootdir)