1 # 通过对NC文件复制来造数据
2 import os, shutil
3
4 # 遍历的根目录
5 root_dir = "D:\\test_data\\DISASTER\\"
6 # 获取NC文件的时间
7 time_source = '20161228080000'
8 # 生成NC文件的时间
9 time_new = '20181228080000'
10
11
12 def get_dir_path(dir_name, time_str):
13 '''
14 组装目录结构
15 :param dir_name:文件名
16 :param time_str:时间字符串,如“20161228080000”
17 :return:目录路径
18 '''
19 dir_path = root_dir + dir_name + '\\' + time_str[0:4] + '\\' + time_str[0:6] + '\\' + time_str[0:8] + '\\'
20 return dir_path
21
22
23 def get_new_file_name(source_file_name, time_source, time_new):
24 '''
25 根据源文件和时间生成新的文件名称
26 :param source_file_name:源文件名
27 :param time_source:源文件时间
28 :param time_new:新文件时间
29 :return: 新的文件名
30 '''
31 list_pices = source_file_name.split('_')
32 # print(list_pices)
33 new_file_name = list_pices[0]
34 for s in list_pices[1:]:
35 if s == time_source:
36 # print(s)
37 new_file_name += '_' + time_new
38 else:
39 new_file_name += '_' + str(s)
40 print("源文件名:", source_file_name)
41 print("新文件名:", new_file_name)
42 return new_file_name
43
44
45 def copy_file(source_file, new_file_name, new_dir):
46 '''
47 拷贝文件,并检查文件是否存在
48 :param source_file: 原文件完整路径包含目录路径和文件名
49 :param new_file_name: 新文件名称
50 :param new_dir: 新文件目录路径
51 :return: 无
52 '''
53 if os.path.exists(new_dir):
54 print("目标目录已存在:", new_dir)
55 else:
56 print('目标目录新建成功!', new_dir)
57 os.makedirs(new_dir) # 创建多级目录
58 # 复制文件
59 new_whole_file = new_dir + new_file_name
60 shutil.copy(source_file, new_whole_file)
61 if os.path.exists(new_whole_file):
62 print("文件复制成功!", new_whole_file)
63 else:
64 print("文件复制失败!", new_whole_file)
65
66
67 def find_and_copy_nc(root_dir, time_source, time_new):
68 '''
69 遍历获取需要拷贝的原NC文件
70 拷贝到新目录下
71 :param root_dir: 文件根目录
72 :param time_source: 源文件时间
73 :param time_new: 目标文件时间
74 '''
75 # 遍历根目录,获取天气现象文件夹列表
76 dir_list = os.listdir(root_dir)
77 for dir in dir_list:
78 '''遍历各天气现象要素目录'''
79 print('#' * 25)
80 print(dir)
81 # 组装源NC文件父目录路径
82 parent_dir = get_dir_path(dir, time_source)
83 print("源目录路径:", parent_dir)
84 new_dir = get_dir_path(dir, time_new)
85 print("目标目录路径:", new_dir)
86 try:
87 '''
88 获取NC文件目录下的文件列表
89 目录不存在就退出循环
90 '''
91 file_list = os.listdir(parent_dir)
92 except:
93 print("源目录不存在:", parent_dir)
94 continue
95
96 for source_file_name in file_list:
97 '''遍历NC文件列表'''
98 if source_file_name.count(time_source) > 0:
99 print('-' * 20)
100 # print("源文件名:", source_file_name)
101 new_file_name = get_new_file_name(source_file_name, time_source, time_new)
102 # print("目标文件名:", new_file_name)
103 copy_file(parent_dir + source_file_name, new_file_name, new_dir)
104
105
106 find_and_copy_nc(root_dir, time_source, time_new)