模拟操作,用python 批量生成0字节文件及进度条

有朋友要解决批量命名文件的问题,把文件名称用txt文件发过来,由于编脚本需要把txt内容写成文件,特编写了小脚本来根据txt生成文件名。

import os
from shutil import copyfile
from shutil import rmtree
import time


path="d:\\1\\4"
print(path)
f1=open(os.path.join(path,'文档目录.txt'),'r')
filelines=f1.readlines()

choose="1"
while choose not in "1|2":
    choose =input("模拟操作:1  实际改名:2  ")
if choose=="1":
    monipath=os.path.join(path,"moni")
    if os.path.exists(monipath):
        rmtree(monipath)
    os.mkdir(monipath)
    f2=open(os.path.join(monipath,'moni'),'w')
    f2.write("")
    f2.flush()
    f2.close()
    for filenum in range(len(filelines)):
        file=filelines[filenum].strip()
        filename=os.path.join(path,file)
        try:
           copyfile(os.path.join(monipath,'moni'),os.path.join(monipath,file))
        except IOError as e:
           print("不能拷贝文件. %s" % e)
           exit()
    os.remove(os.path.join(monipath,'moni'))
    path=monipath

先生成一个moni的0字节文件。然后按txt内容,批量拷贝。

import os
from shutil import copyfile
from shutil import rmtree
import time
from tqdm import tqdm #进度条显示

path="d:\\1\\4"
print(path)
f1=open(os.path.join(path,'文档目录.txt'),'r')
filelines=f1.readlines()
# for i in range(10):
    # file=filelines[i].strip()
    # print(file)


choose="1"

while choose not in "1|2":
    choose =input("模拟操作:1  实际改名:2  ")
if choose=="1":
    monipath=os.path.join(path,"moni")
    if os.path.exists(monipath):
        rmtree(monipath)
    os.mkdir(monipath)
    f2=open(os.path.join(monipath,'moni'),'w')
    f2.write("")
    f2.flush()
    f2.close()
    
    with tqdm(total=len(filelines)) as pbar:
        for filenum in range(len(filelines)):
            pbar.update(1)
            file=filelines[filenum].strip()
            filename=os.path.join(path,file)
            try:
               copyfile(os.path.join(monipath,'moni'),os.path.join(monipath,file))
            except IOError as e:
               print("不能拷贝文件. %s" % e)
               exit()
        os.remove(os.path.join(monipath,'moni'))
        path=monipath
    pbar.close()

为了显示更直观,这个加了进度条,
打开进度条,总计为文件长
with tqdm(total=len(filelines)) as pbar:

每次读取一个文件,加1,实际上每47个一显示
pbar.update(1)

最后要关闭进度条显示 ,如果不加,再运行会加隔行的
pbar.close()

with tqdm(total=1000,miniters=20,unit=“个”) as pbar:
也可以设置最小间隔和数量单位

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值