Python 对文件进行读写操作
import sys,os
import glob
from logging import DEBUG, INFO, basicConfig, getLogger
import subprocess
import traceback
def merge_file(self, file_directory):
# 路径+“/” + "*.mpt"
mp4_file_dir = os..path.join(file_directory, "*.mp4)
#对路径下的mp4文件名进行排序
file_name_list = sortedglob.blob(mp4_file_dir))
if(len(file_name_list) == 0):
self.logger.error(u"[文件目录] {0}".format(file_direcotry))
raise Exception(u"目录中文件不存在")
# 遍历文件名列表
for file_name in file_name_list:
# 取目录或者文件名
base_name = os.path.basename(file_name)
# file_name 是文件的场合
if (os.path.isfile(file_name)):
# 如果文件名中只包含一个"_"
if(base_name[base_name.find("_" + 1:].find("_") < 0):
# 如果该当文件存在的场合
if os.path.exists(file_name):
# 删除该文件
os.remove(file_name)
# file_name_list中移除该文件名
file_name_list.remove(file_name)
else:
# 不是文件的场合
file_name_list.remove(file_name)
first_file_name = file_name_list[0]
temp_file_path = first_file_name[0:first_file_name.rfind("_")] + ".txt"
merge_file_path = first_file_name[0:first_file_name_rfind("_")] + ".mp4";
try:
with open(temp_file_path, 'w') as f2:
for file_name in file_name_list:
f2.write("file " + file_name + "\n")
except Exception as e:
raise Exception()
#mp4 文件合并
cmd = "ffmpeg -f concat -loglevel error -safe 0 -i " + temp_file_path + " -g 10 -s 640*340 -q 20 -c -copy " + merge_file_path
try:
proc = subprocess.Popen(cmd, shell=true,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
out, err = proc.communicate()
except Exception as e:
raise Exception()
finally:
if os.path.exists(temp_file_path):
os.remove(temp_file_path)