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 ...
随机推荐
- 又一次发现Oracle太美之glogin.sql
又一次发现Oracle太美之glogin.sql 刚開始接触Oracle的时候,有时候一登陆一个生产环境.常常会出现以下的情况: [oracle@rh64 app]$ sqlplus / as sys ...
- 0x29 总结与练习
搜索真的菜..困扰了很久,上个星期天没休息好导致整个礼拜没有精神.. 大概完成得七七八八了吧.真是深切的体会到暴力出奇迹的疯狂啊. 3.虫食算 从末位开始枚举判断,通过加数可以推出和的字母代表的数.那 ...
- Oracle 优化和性能调整
分析评价Oracle数据库性能主要有数据库吞吐量.数据库用户响应时间两项指标.数据库用户响应时间又可以分为系统服务时间和用户等待时间两项,即: 数据库用户响应时间=系统服务时间+用户等待时间 因此 ...
- 14. Longest Common Prefix[E]最长公共前缀
题目 Write a function to find the longest common prefix string amongst an array of strings. If there i ...
- Asp.Net Core部署到Linux服务器
从2016年7月, .NET Core1.0 正式发布开始,由于时间问题,我没怎么关注过.NET Core,最近刚抽出点时间研究了下,先讲下如何把ASP.NET Core部署到Linux上吧.这里我用 ...
- 洛谷P1291 [SHOI2002]百事世界杯之旅(期望DP)
题目描述 “……在2002年6月之前购买的百事任何饮料的瓶盖上都会有一个百事球星的名字.只要凑齐所有百事球星的名字,就可参加百事世界杯之旅的抽奖活动,获得球星背包,随声听,更克赴日韩观看世界杯.还不赶 ...
- Activity全屏沉浸状态
public class MainActivity extends AppCompatActivity { private static final String TAG = "MainAc ...
- LA 3635 Pie
题意:给出n个圆,分给n+1个人,求每个人最多能够得到多大面积的圆 二分每个人得到的圆的面积 #include<iostream> #include<cstdio> #incl ...
- 面向对象和结构化程序设计的区别X
面向对象和结构化程序设计的区别 结构化程序的概念首先是从以往编程过程中无限制地使用转移语句而提出的.转移语句可以使程序的控制流程强制性的转向程序的任一处,在传统流程图中,就是用上节我们提到的" ...
- Pyhton学习——Day58
From表单验证 <!DOCTYPE html> <html lang="en"> <head> <meta charset=" ...