文件的复制COPY批处理程序
因为工作中的需要,可能需要对指定文件夹中的特定数据文件进行复制打包,其中我碰到的是在指定文件夹下打包上个月形成的数据,到分好类的13个文件夹中,有一个特点是需打包的数据为上个月的数据,文件名中都包括上个月的日期名‘201907’这样的字符串,所以可以在文件夹中进行历遍,for root,dirs,files in os.walk(path):,对符合的文件进行拷贝。
主要用到了三个包,os进行路径的获取与文件夹的创建,datatime用于获取时间,shutil用于复制文件。
shutil.copy(‘要复制的文件完整路径’,‘复制到的目标文件夹’)
尽量使用相对路径扩大使用度,不需要更改就可以使用在地面观测的电脑上数据打包。
感兴趣的同志,我测试好后打包成exe发给你。目前在我自己的电脑上使用pyinstaller打包成了exe程序,可以脱离python平台使用,在其它电脑上还没测试。
完整程序代码
#Author:Wu Dongqiao
#2019.8.12
#气象地面月数据批量打包程序
#所用到三个包,系统、时间、拷贝
import os
import time
import datetime
import shutil
#若本机无ISOS程序的数据,则退出程序
if not os.path.exists('d:\\isos\\dataset\\'):
print('找不到数据路径')
exit()
#为了打包上个月的数据需获得上个月的月份
today = datetime.date.today() # 获取「今天」
first = today.replace(day=1) # 获取当前月的第一天
yearmonth=first.strftime('%Y%m') #获取当月的年月
last_month = first - datetime.timedelta(days=1) # 减一天,得到上个月的最后一天
YYYYMM=last_month.strftime("%Y%m") # 格式化成指定形式
#设定省份和台站号
if os.listdir('d:\\isos\\dataset\\')[0]=='smo.type':
provin=os.listdir('d:\\isos\\dataset\\')[1]
else:
provin=os.listdir('d:\\isos\\dataset\\')[0]
id=os.listdir('d:\\isos\\dataset\\'+provin)[0]
tempdir='d:\\isos\dataset\\'+provin+'\\'+id+'\\AWS\\' #数据文件名用到的通用路径
temptarge='d:\\'+provin+id+'\\'+YYYYMM+'\\' #目标文件夹用到的通用路径
#指定数据文件夹名列表
datadir=[tempdir+'新型自动站\\订正\\Hour',
tempdir+'新型自动站\\订正\\Minute',
tempdir+'天气现象综合判断\\minute',
tempdir+'weather\\设备\\state\\Minute',
tempdir+'weather\\订正\\value\\Minute',
tempdir+'Visibility\\设备\\state\\Minute',
tempdir+'Visibility\\订正\\value\\Minute',
tempdir+'radiation\\设备\\state\\Minute',
tempdir+'radiation\\订正\\value\\Minute',
tempdir+'sunlight\\设备\\state\\Minute',
tempdir+'sunlight\\订正\\Minute',
tempdir+'weather\\雨滴谱\\minute',
'd:\\isos\\bin\\Awsnet\\'+yearmonth,
'd:\\isos\\bin\\Awsnet\\'+yearmonth]
#指定拷贝到的目标文件夹数组
targedir=[temptarge+'01新型自动站小时数据',
temptarge+'02新型自动站分钟数据',
temptarge+'03天气现象综合判断分钟数据',
temptarge+'04天气现象状态分钟数据',
temptarge+'05天气现象分钟数据',
temptarge+'06能见度状态分钟数据',
temptarge+'07能见度分钟数据',
temptarge+'10辐射状态分钟数据',
temptarge+'11辐射分钟数据',
temptarge+'12日照状态分钟数据',
temptarge+'13日照分钟数据',
temptarge+'14谱数据文件',
temptarge+'15降水现象自动观测分钟数据zip格式压缩上传文件',
temptarge+'16降水现象观测数据整编文件']
#循环查找并拷贝
for i in range(14):
for root,dirs,files in os.walk(datadir[i]):
#判断目标文件夹是否存在,不存在则创建目标文件夹
if not os.path.exists(targedir[i]):
os.makedirs(targedir[i])
for file in files:
if i<12:
if YYYYMM in file:
shutil.copy(os.path.join(root,file),targedir[i])
elif i==12:
if 'weather-VALUE-'+YYYYMM in file:
shutil.copy(os.path.join(root, file), targedir[i])
elif i==13:
if 'weather-TEMP-'+YYYYMM in file:
shutil.copy(os.path.join(root, file), targedir[i])
print("月上传数据打包完成,目标文件夹D:\\"+provin+id+'\\'+YYYYMM)
time.sleep(3) #三秒后退出程序
我以为打包这多文件会要几秒的时间,结果不到一秒就全部处理完,效率还是相当快的。