python 文件操作 os模块和shutil模块

转载自:http://www.cnblogs.com/rollenholt/archive/2012/04/23/2466179.html


############################################################################


python中对文件 / 文件夹的操作涉及到os模块和shutil模块


[python]  view plain  copy
  1. import os  
  2. import shutil  

##################################################################3


得到当前目录路径:

[python]  view plain  copy
  1. os.getcwd()  

返回指定目录path下的所有文件和目录名:
[python]  view plain  copy
  1. os.listdir(path)  

删除一个文件:

[python]  view plain  copy
  1. os.remove(path)  

判断给出路径是否为一个文件:
[python]  view plain  copy
  1. os.path.isfile()  

判断给出的路径是否为一个目录:
[python]  view plain  copy
  1. os.path.isdir()  

判断给出的路径是否是绝对路径:
[python]  view plain  copy
  1. os.path.isabs()  

判断给出的路径是否真实存在:
[python]  view plain  copy
  1. os.path.exists()  
返回False如果是一个错误的符号链接


分离给定路径的目录名和文件名:

[python]  view plain  copy
  1. os.path.split(p)  


分离扩展名:

[python]  view plain  copy
  1. os.path.splitext(p)  
扩展名可能为空



获取路径名:

[python]  view plain  copy
  1. os.path.dirname(p)  

获取文件名:
[python]  view plain  copy
  1. os.path.basename(p)  



重命名:

[python]  view plain  copy
  1. os.rename(old, new)  
可以重命名一个文件或一个目录




创建多级目录:

[python]  view plain  copy
  1. os.makedirs(path)  

创建单个目录:
[python]  view plain  copy
  1. os.mkdir(path)  

复制文件:

[python]  view plain  copy
  1. shutil.copyfile(src, dst)  
复制数据从src到dst(src和dst均为文件)

[python]  view plain  copy
  1. shutil.copy(src, dst)  
复制数据从src到dst(src为文件,dst可以为目录)


复制文件夹:

[python]  view plain  copy
  1. shutil.copytree(src, dst)  
递归复制文件夹,其中,src和dst均为目录,且dst不存在


移动目录(文件):

[python]  view plain  copy
  1. shutil.move(src, dst)  
递归移动一个文件或目录到另一个位置,类似于"mv"命令


删除目录:

[python]  view plain  copy
  1. shutil.rmtree(path)  

递归删除一个目录(有内容,空的均可)


程序:重命名图片,在原图片名后加上“_fc”字符串

[python]  view plain  copy
  1. #!/usr/local/env python  
  2. #-*- coding: utf-8 -*-  
  3.   
  4. import re  
  5. import os  
  6. import time  
  7.   
  8. def change_name(path):  
  9.     global i #定义全局变量  
  10.     if not os.path.isdir(path) and not os.path.isfile(path): #判断是否是目录或文件  
  11.         return False  
  12.     if os.path.isfile(path): #如果是文件  
  13.         file_path=os.path.split(path) #分割出目录与文件名  
  14.         lists=file_path[1].split('.'#分割出文件与文件扩展名  
  15.         file_ext=lists[-1#取出后缀名  
  16.         img_ext=['bmp''jpeg''gif''psd''png''jpg']  
  17.         if file_ext in img_ext:  #判断该后缀名是否是图片的后缀名  
  18.             os.rename(path, file_path[0]+"/"+lists[0]+"_fc."+file_ext)  
  19.             i+=1  
  20.     elif os.path.isdir(path): #如果是目录  
  21.         for x in os.listdir(path): #递归重命名程序  
  22.             change_name(os.path.join(path,x))  
  23.   
  24. img_dir=os.getcwd()+"/snsc" #取得图片文件夹路径  
  25. start=time.time() #计时  
  26. i=0 #初始化计算器i为0  
  27. change_name(img_dir) #开始重命名程序  
  28. c=time.time()-start  
  29. print "程序运行耗时:%0.2f"%c  
  30. print "总共处理了%d张图片"%i  

猜你喜欢

转载自blog.csdn.net/helei001/article/details/78948156