设为首页 加入收藏

TOP

Python文件和目录操作方法(二)
2017-08-20 10:22:52 】 浏览:505
Tags:Python 文件 目录 操作 方法
的大小,也可能是以一些随机的内容加上去。
三、目录操作方法大全
1.创建目录
os.mkdir("file")                 
2.复制文件:
shutil.copyfile("oldfile","newfile")        #oldfile和newfile都只能是文件
shutil.copy("oldfile","newfile")            #oldfile只能是文件夹,newfile可以是文件,也可以是目标目录
3.复制文件夹:
4.shutil.copytree("olddir","newdir")        #olddir和newdir都只能是目录,且newdir必须不存在
5.重命名文件(目录)
os.rename("oldname","newname")              #文件或目录都是使用这条命令
6.移动文件(目录)
shutil.move("oldpos","newpos") 
7.删除文件
os.remove("file")
8.删除目录
os.rmdir("dir")                            #只能删除空目录
shutil.rmtree("dir")                        #空目录、有内容的目录都可以删
9.转换目录
os.chdir("path")                            #换路径


四、文件综合操作实例
将文件夹下所有图片名称加上'_fc'
python代码:


# -*- coding:utf-8 -*-
import re
import os
import time
#str.split(string)分割字符串
#'连接符'.join(list) 将列表组成字符串
def change_name(path):
    global i
    if not os.path.isdir(path) and not os.path.isfile(path):
        return False
    if os.path.isfile(path):
        file_path = os.path.split(path) #分割出目录与文件
        lists = file_path[1].split('.') #分割出文件与文件扩展名
        file_ext = lists[-1] #取出后缀名(列表切片操作)
        img_ext = ['bmp','jpeg','gif','psd','png','jpg']
        if file_ext in img_ext:
            os.rename(path,file_path[0]+'/'+lists[0]+'_fc.'+file_ext)
            i+=1 #注意这里的i是一个陷阱
        #或者
        #img_ext = 'bmp|jpeg|gif|psd|png|jpg'
        #if file_ext in img_ext:
        #    print('ok---'+file_ext)
    elif os.path.isdir(path):
        for x in os.listdir(path):
            change_name(os.path.join(path,x)) #os.path.join()在路径处理上很有用
img_dir = 'D:\xx\\xx\images'27 start = time.time()
i = 0
change_name(img_dir)
c = time.time() - start
print('程序运行耗时:%0.2f'%(c))
print('总共处理了 %s 张图片'%(i))


输出结果:


程序运行耗时:0.50
总共处理了 41 张图片


首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇使用Spring注解获取配置文件信息 下一篇ArrayList 和 LinkedList的执行效..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目