本文主要是介绍WRF如何批量输出文件添加或删除文件名后缀,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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 + '.nc'os.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)
这篇关于WRF如何批量输出文件添加或删除文件名后缀的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!