背景故事:录音文件备份,从一台服务器A,备份到另一台服务器B,之后再将已经备份完的录音文件保存7天后从A服务器上删除。这篇代码是从网上扒拉出几段,组合上去的。
#coding=utf-8
import os
import codecs
import argparse
import request
import time
import wave
import shutil
import datatime
#上面导包的模块不懂的自行百度
#运行脚本需要的支持 python3 相关类库版本要匹配的,requests-2.18.4 certifi-2017.4.17 chardet-3.0.4 idna-2.6 urllib3-1.22
all_file_list = set()
new_upload_filelist = []
upload_server = "http://27.0.0.0:8080/record.action"
#定义一个方法,循环遍历拿取录音文件
def get_all_filepath(dir):
parents = os.listdir(dir)
for parent in parents:
child = os.path.join(dir,parent)
if os.path.isdir(child):
get_all_filepath(child)
else:
all_file_list.add(child)
'''
pcm转换为wav格式
Args:
pcm_file pcm文件
save_file 保存文件
channels 通道数
bits 量化位数,即每个采样点占用的比特数
sample_rate 采样频率
'''
def pcm2wav(pcm_file, save_file, channels=1, bits=16, sample_rate=16000):
pcmf = open(pcm_file, 'rb')
pcmdata = pcmf.read()
pcmf.close()
print('zhuanhuanlema')
if bits % 8 != 0:
raise ValueError("bits % 8 must == 0. now bits:" + str(bits))
wavfile = wave.open(save_file, 'wb')
wavfile.setnchannels(channels)
wavfile.setsampwidth(bits // 8)
wavfile.setframerate(sample_rate)
wavfile.writeframes(pcmdata)
wavfile.close()
def upload_one_file(filepath):
#上传一个文件到服务器
# 从文件名得到各个字段
filename = filepath.replace("\\","/").split("/")[-1]
filename_parts = filename.split("_")
# 5段:
# sessionid cstno starttime endtime strVoiceId
if len(filename_parts) != 5:
return 1
sessionid = filename_parts[0]
cstno = filename_parts[1]
starttime = filename_parts[2]
endtime = filename_parts[3]
voiceid = filename_parts[4]
#时间戳转换
start_time_array = time.localtime(int(starttime))
start_time_formated = time.strftime("%Y-%m-%d %H:%M:%S", start_time_array)
end_time_array = time.localtime(int(endtime))
end_time_formated = time.strftime("%Y-%m-%d %H:%M:%S", end_time_array)
try:
wav_file=os.path.splitext(filepath)[0]+".wav"
pcm2wav(filepath, wav_file, channels=1, bits=16, sample_rate=16000)
except Exception as e:
print('Convert fail: '+ filepath)
file = {'audiofile':open(wav_file,'rb')}
params = {'sessionid': sessionid, 'cstno': cstno,'starttime':start_time_formated,'endtime':end_time_formated }
response = requests.post(upload_server,data=params,files=file)
return 0
def upload_new_file():
for filepath in all_file_list:
ret=upload_one_file(filepath)
if ret ==0:
print("upoload success")
dir_already='/data/qcloud/alreadyup'+datetime.datetime.now().strftime("%Y%m%d")+'/'
print(datetime.datetime.now().strftime("%Y%m%d"))
if os.path.exists(dir_already):
print("already exists")
else:
os.makedirs(dir_already)
#shutil.move(filepath,dir_already)
#shutil.move(os.path.splitext(filepath)[0]+".wav",dir_already)
else:
print("upload fail" + filepath)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='')
parser.add_argument('upload_dir', type=str, help='upload_dir')
args = parser.parse_args()
upload_dir = args.upload_dir
get_all_filepath(upload_dir)
upload_new_file()