实用Python代码小工具集合

1. 删除文本文档中的空行;

# coding:utf-8 

file1 = open('clean.txt', 'r', encoding='utf-8')   # 打开要去掉空行的文件
file2 = open('clean2.txt', 'w', encoding='utf-8')  # 生成没有空行的文件

for line in file1.readlines():
    if line == '\n':
        line = line.strip('\n')
    file2.write(line)

file1.close()
file2.close()

2.  批量修改文件夹中的文件名;

#批量修改文件名
#批量修改图片文件名
import os
import re
import sys
def renameall():
	fileList = os.listdir(r"文件目录")		#待修改文件夹
	print("修改前:"+str(fileList))		#输出文件夹中包含的文件
	currentpath = os.getcwd()		#得到进程当前工作目录
	os.chdir(r"文件目录")		#将当前工作目录修改为待修改文件夹的位置
	num=1		#名称变量
	for fileName in fileList:		#遍历文件夹中所有文件
		pat=".+\.(jpg|png|gif|py|txt)"		#匹配文件名正则表达式
		pattern = re.findall(pat,fileName)		#进行匹配
		os.rename(fileName,(str(num)+'.'+pattern[0]))		#文件重新命名
		num = num+1		#改变编号,继续下一项
	print("---------------------------------------------------")
	os.chdir(currentpath)		#改回程序运行前的工作目录
	sys.stdin.flush()		#刷新
	print("修改后:"+str(os.listdir(r"文件目录")))		#输出修改后文件夹中包含的文件
renameall()

3. 从文件夹中删除文本文档中列表的文件

import os
path = "文件目录"
os.chdir(path)
flist = open('clean.txt')
for f in flist:
    fname = f.rstrip() # or depending on situation: f.rstrip('\n')
    # or, if you get rid of os.chdir(path) above,
    # fname = os.path.join(path, f.rstrip())
    if os.path.isfile(fname): # this makes the code more robust
        os.remove(fname)

# also, don't forget to close the text file:
flist.close()

4. 批量截取文件夹下的视频的图片并保存在视频同名的文件夹中;

import cv2
import os

i = 0
j = 0
filepath = 'E:\\Marketing\\clip'
pathDir = os.listdir(filepath)
save_filename = 'E:\\Marketing\\clip\\'
timeF = 5 #截图时间间隔
class Nstr:
    def __init__(self, arg):
       self.x=arg
    def __sub__(self,other):
        c=self.x.replace(other.x,"")
        return c

def saveImage(frame, SaveAddress, num):
    try:
        address = SaveAddress + "/" + str(num) + '.jpg'
        cv2.imencode('.jpg', frame)[1].tofile(address)
        print(num)
    except Exception:
        print(address)


for allDir in pathDir:
    videopath = filepath + '/' + allDir
    name = videopath.split("/")[1]
    if name[-4:] == ".mkv":
        new_name = Nstr(name) - Nstr(name[-4:])
        save_file = os.path.join(save_filename, new_name)
        if not os.path.exists(save_file):
            os.mkdir(save_file)
        videoCapture = cv2.VideoCapture(videopath)
        if videoCapture.isOpened():  # 判断是否正常打开
            rval, frame = videoCapture.read()
        else:
            rval = False
            print("false")
        while rval:
            rval, frame = videoCapture.read()
            i += 1
            if (i%timeF==0):
                j += 1
                saveImage(frame, save_file, j)
                pass

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值