Python学习笔记--OS模块对文件操作

 基础语法

下面是Python的常用语法示例,可供参考

Python文件操作用到的常用模块就是os模块和shutil模块

os.getcwd()--当前Python脚本工作的目录路径

os.listdir()--以列表的形式返回指定目录下的所有文件和目录名

os.remove()--删除1个文件

os.path.isfile()--检验给出的路径是否是1个文件

os.path.isdir()--检验给出的路径是否是1个目录

os.path.isabs()--检验给出的是绝对路径

os.path.exists()--检验给出的是否是真实路径

os.path.split()--以元组的形式返回1个路径的目录名和文件名

  1. os.path.split("F:/F:/hello/qq/Koala.jpg")
  2. >>>('F:/F:/hello/qq', 'Koala.jpg')

os.path.splitext()--分离扩展名

OS.path.dirname()--获取路径名

os.path.basename()--获取文件名

os.linesep --给出当前平台的行终止符,Windows使用'\r\n',Linux使用'\n'而Mac使用'\r'

os.rename(old,new) --重命名

os.makedirs(r"C/python/test/") --创建多级目录

os.mkdir("test")--创建单个目录

os.path.join(path,x)--拼接路径

代码示例

 1 # -*- coding:UTF-8 -*-
 2 import os
 3 
 4 
 5 Path2="F:/hello/qq/"
 6 
 7 def change_name(path):
 8     if not os.path.exists(path):
 9         return False
10     if not os.path.isfile(path) and not os.path.isdir(path):
11         return False
12     if os.path.isfile(path):
13         filename = os.path.splitext(path) #分离出文件与扩展名
14         print filename
15         img_ext = ['.bmp','.jpeg','.gif','.psd','.png','.jpg']
16         if filename[1] in img_ext:
17             os.rename(path,filename[0]+"_gc"+filename[1])
18     elif os.path.isdir(path):
19         for x in os.listdir(path):
20             change_name(os.path.join(path,x))
21 
22 change_name(Path2)

 


猜你喜欢

转载自www.cnblogs.com/dongliping/p/11405460.html
今日推荐