python解压,压缩,以及存数据库的相关操作
import os,shutil,zipfile,glob def dfs_get_zip_file(input_path,result): #
files = os.listdir(input_path)
for file in files:
if os.path.isdir(input_path+'/'+file):
dfs_get_zip_file(input_path+'/'+file,result)
else:
result.append(input_path+'/'+file) def zip_path(input_path,output_path,output_name): f = zipfile.ZipFile(output_path+'/'+output_name,'w',zipfile.ZIP_DEFLATED)
filelists = []
dfs_get_zip_file(input_path,filelists)
for file in filelists:
f.write(file)
f.close()
return output_path+r"/"+output_name zip_path(r"./10",'D:','wok.zip')
将数据存入到数据库
#coding:utf-8
import sys
reload(sys)
sys.setdefaultencoding('utf8') import mysql.connector conn =mysql.connector.connect(user='root',password='bytebear2017',host='sh-cdb-myegtz7i.sql.tencentcdb.com',database='bitbear',charset='utf8') cursor = conn.cursor() #cursor.execute('create table usertest (id varchar(20) primary key, name varchar(20))') cursor.execute('insert into usertest1 (id, name) values (%s, %s)', ['', 'Michael']) cursor.rowcount conn.commit() cursor.close()
完整流程
#coding:utf-8
import sys
import importlib
importlib.reload(sys) import mysql.connector
import os,shutil,zipfile,glob # 视频唯一索引命名规则 'rtmp://111.231.109.254:10085/bitbear'.date(format:'ymd').$course_id.$num.$user_id
filename='1-10.zip'; #-----------解压缩并获取用户id------------
def unzip():
# 默认模式r,读
azip = zipfile.ZipFile(filename) #for file in azip.namelist():
# azip.extract(file, r'./1-10')
azip.extractall()
# 返回所有文件夹和文件
#print(azip.namelist())
# # 返回该zip的文件名
#print(azip.filename) # 遍历filename,按照索引命名规则,取出用户id
userid=''
state = 0
for i in filename:
if(i=='-'):
state = 1
elif(state==1 and i=='.'):
break;
elif(state==1):
userid=userid+i
return userid; # ----------创建目录---------------
# 利用该用户的id,创建一个以id命名的该用户的目录
def mkdir(path):
# 去除首位空格
path=path.strip()
# 去除尾部 \ 符号
path=path.rstrip("\\")
# 判断路径是否存在
isExists=os.path.exists(path)
if not isExists:
os.makedirs(path)
print (path+' 创建成功')
return True
else:
print (path+' 目录已存在')
return False #-------------------压缩------------------
# 利用的是对目录进行深度优先遍历,首先把第一级目录中的文件进行遍历,
# 如果是文件,则把它连同当前路径一起加入result(list),如果是子目录,则在整个目录上继续DFS。直到所有的文件都被加入。
# 参考http://blog.csdn.net/wangtua/article/details/68943231
def dfs_get_zip_file(input_path,result): #
files = os.listdir(input_path)
for file in files:
if os.path.isdir(input_path+'/'+file):
dfs_get_zip_file(input_path+'/'+file,result)
else:
result.append(input_path+'/'+file) def zip_path(input_path,output_path,output_name): f = zipfile.ZipFile(output_path+'/'+output_name,'w',zipfile.ZIP_DEFLATED)
filelists = []
dfs_get_zip_file(input_path,filelists)
for file in filelists:
f.write(file)
f.close()
return output_path+r"/"+output_name #-----------------------------将地址存入数据库-------------- def todatabase():
rarpath = os.getcwd(); # 获得当前路径
rarpath = rarpath+'\\10.zip'
#print(rarpath)
conn =mysql.connector.connect(user='root',password='bytebear2017',host='sh-cdb-myegtz7i.sql.tencentcdb.com',port='',database='bitbear',charset='utf8')
cursor = conn.cursor()
#cursor.execute('create table usertest (id varchar(20) primary key, name varchar(20))')
cursor.execute('insert into usertest1 ( name) values ( %s)', [rarpath])
cursor.rowcount
if(conn.commit()==1):
print('插入数据库成功')
cursor.close() #----------------------------主程序部分---------------------------------
#解压
userid=unzip() # 创建目录
mkpath='./'+userid
mkdir(mkpath) # 把123123123123.flv和json目录放到123456789目录下
srcfile='./1-10'
dstfile='./10'
shutil.move(srcfile,dstfile) # 压缩
zip_path(r"./10",'./','10.zip') # 存入数据库
todatabase()
0204修改
#coding:utf-8
import sys
import importlib
importlib.reload(sys) import mysql.connector
import os,shutil,zipfile,glob # 视频唯一索引命名规则 'rtmp://111.231.109.254:10085/bitbear/'.date(format:'ymd').'-'.$course_id.'-'.$num.'-'.$user_id
#filename = './video/20180204-10-1-10.zip';
path1 = './video/'; # 扫描目录
def showdata():
dir=path1
if os.path.exists(dir):
dirs = os.listdir(dir)
#dirs.sort(compare)
#dirs.reverse()
dirs.sort()
if not dirs:
nowTime=datetime.datetime.now().strftime('Not Find Video...%Y-%m-%d %H:%M:%S')
print(nowTime)
return "",0
for dirc in dirs:
size = os.path.getsize(os.path.join(dir, dirc))
#print(dirc)
#print(size)
return dirc,size # ----------创建目录---------------
# 利用该用户的id,创建一个以id命名的该用户的目录
def mkdir(path):
# 去除首位空格
path=path.strip()
# 去除尾部 \ 符号
path=path.rstrip("\\")
# 判断路径是否存在
isExists=os.path.exists(path)
if not isExists:
os.makedirs(path)
print (path+' 创建成功')
return True
else:
print (path+' 目录已存在')
return False #-----------移动到video文件夹------------
def tovideo(filename_new): # 读取用户id,课程名
userid=''
course_id='' # 在outfile文件夹创建目录
mkpath='./outfile/'+userid
mkdir(mkpath) # 将视频移动到./outfile/userid/ 下
srcfile='./video/'+filename_new
dstfile=mkpath
shutil.move(srcfile,dstfile) # 解压
azip = zipfile.ZipFile(mkpath+'/'+filename_new)
azip.extractall(mkpath+'/')
print(mkpath+'/'+filename_new) #os.remove(mkpath+'/'+filename_new) return userid,course_id def zip(path): print(path)
os.remove(path) if __name__ == "__main__": (filename_new, filesize_new ) = showdata()
print(filename_new)
(userid, course_id) = tovideo(filename_new)
#unzip('20180204-10-1-10.zip')
zip('./outfile/'+userid+'/'+filename_new)
#coding:utf-8
import sys
import importlib
importlib.reload(sys) import mysql.connector
import os,shutil,zipfile,glob # 视频唯一索引命名规则 'rtmp://111.231.109.254:10085/bitbear/'.date(format:'ymd').'-'.$course_id.'-'.$num.'-'.$user_id
#filename = './video/20180204-10-1-10.zip';
path1 = './video/'; # goutfile为全局的从outfile目录传到web目录的压缩文件名
global gfilename_new,guserid,gcourse_id,gout # 扫描目录
def showdata():
dir=path1
if os.path.exists(dir):
dirs = os.listdir(dir)
#dirs.sort(compare)
#dirs.reverse()
dirs.sort()
if not dirs:
nowTime=datetime.datetime.now().strftime('Not Find Video...%Y-%m-%d %H:%M:%S')
print(nowTime)
return "",0
for dirc in dirs:
size = os.path.getsize(os.path.join(dir, dirc))
#print(dirc)
#print(size)
return dirc,size # ----------创建目录---------------
# 利用该用户的id,创建一个以id命名的该用户的目录
def mkdir(path):
# 去除首位空格
path=path.strip()
# 去除尾部 \ 符号
path=path.rstrip("\\")
# 判断路径是否存在
isExists=os.path.exists(path)
if not isExists:
os.makedirs(path)
print (path+' 创建成功')
return True
else:
print (path+' 目录已存在')
return False #-----------移动到video文件夹------------
def tovideo(filename_new): # 读取用户id,课程名
userid=''
course_id='' # 在outfile文件夹创建目录
mkpath='./outfile/'+userid
mkdir(mkpath) # 将视频移动到./outfile/userid/ 下
srcfile='./video/'+filename_new
dstfile=mkpath
shutil.move(srcfile,dstfile) # 解压
azip = zipfile.ZipFile(mkpath+'/'+filename_new)
azip.extractall(mkpath+'/')
print(mkpath+'/'+filename_new) #os.remove(mkpath+'/'+filename_new) return userid,course_id def zip():
startdir = "./outfile/10" #要压缩的文件夹路径
file_news = 'archive.zip' # 压缩后文件夹的名字
z = zipfile.ZipFile(file_news,'w',zipfile.ZIP_DEFLATED) #参数一:文件夹名
for dirpath, dirnames, filenames in os.walk(startdir):
fpath = dirpath.replace(startdir,'') #这一句很重要,不replace的话,就从根目录开始复制
fpath = fpath and fpath + os.sep or ''#这句话理解我也点郁闷,实现当前文件夹以及包含的所有文件的压缩
for filename in filenames:
z.write(os.path.join(dirpath, filename),fpath+filename)
print ('压缩成功')
z.close() # 将压缩文件传到web文件夹
def toweb():
# 将视频移动到./web 下
global gout
srcfile='./outfile/'+guserid+'/'+gout
#print(srcfile)
dstfile='./web/'
shutil.move(srcfile,dstfile) if __name__ == "__main__": (gfilename_new, filesize_new ) = showdata()
print(gfilename_new)
(guserid, gcourse_id) = tovideo(gfilename_new)
#unzip('20180204-10-1-10.zip')
#zip('./outfile/'+guserid+'/'+filename_new)
zip_path(r"./outfile/"+guserid,'./outfile/'+guserid,gcourse_id+'-'+guserid+'.zip')
gout = gcourse_id+'-'+guserid+'.zip'
#toweb()
最新
#_*_ coding:utf-8 _*_
import datetime
import time
import os
import os.path
import cv2
import numpy as np import os,shutil,zipfile,glob #视频唯一索引组织方式:date('ymd').'-'$couse_id.'-'.$num.'-'.$total_num.'-'.$user_id
global gfilename,guser_id,gcourse_id,gnum,gtotal_num
videopath = './video/'; # 扫描目录
def showdata():
dir=videopath
if os.path.exists(dir):
dirs = os.listdir(dir)
#dirs.sort(compare)
#dirs.reverse()
dirs.sort()
if not dirs:
nowTime=datetime.datetime.now().strftime('Not Find Video...%Y-%m-%d %H:%M:%S')
print(nowTime)
return "",0
for dirc in dirs:
size = os.path.getsize(os.path.join(dir, dirc))
#print(dirc)
#print(size)
return dirc,size # ----------创建目录---------------
# 利用该用户的id,创建一个以id命名的该用户的目录
def mkdir(path):
# 去除首位空格
path=path.strip()
# 去除尾部 \ 符号
path=path.rstrip("\\")
# 判断路径是否存在
isExists=os.path.exists(path)
if not isExists:
os.makedirs(path)
print (path+' 创建成功')
return True
else:
print (path+' 目录已存在')
return False #-----------移动到video文件夹------------
def tooutfile():
global gfilename,guser_id,gcourse_id,gnum,gtotal_num # 读取用户id,课程名
count=0
gcourse_id=''
guser_id=''
gnum=''
gtotal_num=''
for i in gfilename:
if(i=='-'):
count = count+1
if(count==1 and i!='-'):
gcourse_id=gcourse_id+i
if(count==2 and i!='-'):
gnum=gnum+i
if(count==3 and i!='-'):
gtotal_num=gtotal_num+i
if(count==4 and i!='-' and i!='.'):
guser_id=guser_id+i
if(i=='.'):
break
#print(guser_id)
#print(gcourse_id)
#print(gnum)
#print(gtotal_num) # 在outfile文件夹创建目录
mkpath='./outfile/'+guser_id
mkdir(mkpath) # 将视频移动到./outfile/userid/ 下
srcfile='./video/'+gfilename
dstfile=mkpath
shutil.move(srcfile,dstfile) #合并视频的部分
combinepath = './outfile/10/' def CreateFile(videoWriter,filename):
cap = cv2.VideoCapture('./outfile/10/'+filename)
if (cap.isOpened() == False):
print("Unable to read camera feed1")
# fps = cap.get(cv2.CAP_PROP_FPS)
# size = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),
# int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
success, frame = cap.read()
while success :
videoWriter.write(frame)
success, frame = cap.read() def CreateFile_old(filename):
# Create a VideoCapture object
# cap = cv2.VideoCapture('../video/test.avi')
cap = cv2.VideoCapture('../video/'+filename)
# Check if camera opened successfully
if (cap.isOpened() == False):
print("Unable to read camera feed")
frame_width = int(cap.get(3))
frame_height = int(cap.get(4))
out = cv2.VideoWriter('../outpy/out.avi',cv2.VideoWriter_fourcc('F', 'L', 'V', ''), 14, (frame_width,frame_height))
# out = cv2.VideoWriter('../outpy/'+filename,cv2.VideoWriter_fourcc('F', 'L', 'V', '1'), 14, (frame_width,frame_height))
while(True):
ret, frame = cap.read()
if ret == True:
out.write(frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
cap.release()
# out.release()
cv2.destroyAllWindows() def ErgodCatalog():
dir=combinepath
if os.path.exists(dir):
dirs = os.listdir(dir)
#dirs.sort(compare)
#dirs.reverse()
dirs.sort()
videoWriter = cv2.VideoWriter('./outfile/10/out.avi', cv2.VideoWriter_fourcc('F', 'L', 'V', ''), 30.0, (360, 640))
if not dirs:
time.sleep(1)
print("Sleep 1S")
return 0
for dirc in dirs:
size = os.path.getsize(os.path.join(dir, dirc))
# CreateFile(dirc)
CreateFile(videoWriter,dirc)
print("name:",dirc,",size:",size)
return 0 #while(True):
# ErgodCatalog() if __name__ == "__main__":
#global gfilename,guser_id,gcourse_id,gnum,gtotal_num
#ErgodCatalog()
#while(True):
(gfilename, filesize) = showdata()
if(gfilename!=''): # 在文件夹中有视频存在时,才进行以下操作
print(gfilename)
tooutfile() #将video文件夹中的视频移动到outfile
if(gnum==gtotal_num): #在训练的组数达到总组数时,将视频合并
ErgodCatalog() #(gfilename, filesize) = showdata()
#print(gfilename)
#(guserid, gcourse_id) = tovideo() #ErgodCatalog()
报错的写法
#合并视频的部分
combinepath = './outfile/10/' def CreateFile(videoWriter,filename):
cap = cv2.VideoCapture('./outfile/10/'+filename)
if (cap.isOpened() == False):
print("Unable to read camera feed1")
# fps = cap.get(cv2.CAP_PROP_FPS)
# size = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),
# int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
success, frame = cap.read()
while success :
videoWriter.write(frame)
success, frame = cap.read() def CreateFile_old(filename):
# Create a VideoCapture object
# cap = cv2.VideoCapture('../video/test.avi')
cap = cv2.VideoCapture('../video/'+filename)
# Check if camera opened successfully
if (cap.isOpened() == False):
print("Unable to read camera feed")
frame_width = int(cap.get(3))
frame_height = int(cap.get(4))
out = cv2.VideoWriter('../outpy/out.avi',cv2.VideoWriter_fourcc('F', 'L', 'V', ''), 14, (frame_width,frame_height))
# out = cv2.VideoWriter('../outpy/'+filename,cv2.VideoWriter_fourcc('F', 'L', 'V', '1'), 14, (frame_width,frame_height))
while(True):
ret, frame = cap.read()
if ret == True:
out.write(frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
cap.release()
# out.release()
cv2.destroyAllWindows() def ErgodCatalog():
dir=combinepath
if os.path.exists(dir):
dirs = os.listdir(dir)
#dirs.sort(compare)
#dirs.reverse()
dirs.sort()
videoWriter = cv2.VideoWriter('./outfile/10/out.avi', cv2.VideoWriter_fourcc('F', 'L', 'V', ''), 30.0, (360, 640))
if not dirs:
time.sleep(1)
print("Sleep 1S")
return 0
for dirc in dirs:
size = os.path.getsize(os.path.join(dir, dirc))
# CreateFile(dirc)
CreateFile(videoWriter,dirc)
print("name:",dirc,",size:",size)
return 0
python解压,压缩,以及存数据库的相关操作的更多相关文章
- python 解压 压缩包
转 http://m.blog.csdn.net/blog/wice110956/26597179# 这里讨论使用Python解压如下五种压缩文件: .gz .tar .tgz .zip .rar ...
- python解压压缩包的几种方法
这里讨论使用Python解压例如以下五种压缩文件: .gz .tar .tgz .zip .rar 简单介绍 gz: 即gzip.通常仅仅能压缩一个文件.与tar结合起来就能够实现先打包,再压缩. ...
- python 解压、复制、删除 文件
一.python3解压文件 1.python 解压文件代码示例 如下代码主要实现zip.rar.tar.tar.gz四种格式的压缩文件的解压 def unzip_file(src_file, dst_ ...
- python解压压缩包的几种方式
这里讨论使用Python解压如下五种压缩文件: .gz .tar .tgz .zip .rar 简介 gz: 即gzip,通常只能压缩一个文件.与tar结合起来就可以实现先打包,再压缩. tar: ...
- python操作mysql数据库的相关操作实例
python操作mysql数据库的相关操作实例 # -*- coding: utf-8 -*- #python operate mysql database import MySQLdb #数据库名称 ...
- PHP对MySQL数据库的相关操作
一.Apache服务器的安装 <1>安装版(计算机相关专业所用软件---百度云链接下载)-直接install<2>非安装版(https://www.apachehaus.com ...
- python字符串、字符串处理函数及字符串相关操作
python字符串.字符串处理函数及字符串相关操作 字符串介绍 python字符串表示 Python除处理数字外还可以处理字符串,字符串用单撇号或双撇号包裹: >>> 'spam e ...
- Python解压ZIP、RAR等常用压缩格式的方法
解压大杀器 首先祭出可以应对多种压缩包格式的python库:patool.如果平时只用基本的解压.打包等操作,也不想详细了解各种压缩格式对应的python库,patool应该是个不错的选择. pato ...
- python怎么解压压缩的字符串数据
范例1: gzip import StringIO import gzip compresseddata = gzip方式压缩的字符串(html) compressedstream = StringI ...
随机推荐
- Nagios监控nginx服务具体过程
1在nginx 服务器上安装nrpe客户端: Nginx的服务须要监控起来.不然万一down了而不及时修复,会影响web应用.例如以下web应用上面启动的nginx后台进程[root@lb-net-2 ...
- Hadoop自学笔记(二)HDFS简单介绍
1. HDFS Architecture 一种Master-Slave结构.包括Name Node, Secondary Name Node,Data Node Job Tracker, Task T ...
- UVA - 11021 - Tribles 递推概率
GRAVITATION, n.“The tendency of all bodies to approach one another with a strengthproportion to the ...
- angularjs1-5,class,
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content ...
- EM无法登录,提示ORA-28001: the password has expired (DBD ERROR: OCISessionBegin)
--查看数据库目前的口令期限 sys@TESTDB11>select * from dba_profiles where profile = 'DEFAULT' and resource_nam ...
- Spark Streaming概念学习系列之SparkStreaming运行原理
SparkStreaming运行原理 Spark Streaming不断的从数据源获取数据(连续的数据流),并将这些数据按照周期划分为batch. Spark Streaming将每个batch的数据 ...
- Core篇——初探Core配置管理
文章目录 1.命令行配置 2.Json文件配置 3.配置文件文本至C#对象实例的映射 4.配置文件热更新 5.总结 命令行的配置 我们首先来创建一个.net core 的控制台项目,然后引入.net ...
- UWP 开发相关
OCR 识别问题 ocr.OcrEngine.availableRecognizerLanguages 如果 length 只有 1,有可能只能识别英文,需要安装中文语言包~
- vue中使用Ueditor编辑器 -- 1
一. 下载包: 从Ueditor的官网下载1.4.3.3jsp版本的Ueditor编辑器,官网地址为:http://ueditor.baidu.com/website/download.html ...
- px 与 pt
px:pixel,像素,屏幕上显示的最小单位,用于网页设计,直观方便: pt:point,是一个标准的长度单位,1pt=1/72英寸,用于印刷业,非常简单易用: em:即%,在CSS中,1em=100 ...