zoukankan      html  css  js  c++  java
  • 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使用' ',Linux使用' '而Mac使用' '

    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 i=0
     7 
     8 def change_name(path):
     9     global i
    10     if not os.path.exists(path):
    11         return False
    12     if not os.path.isdir(path) and not os.path.isfile(path):
    13         return False
    14     if os.path.isfile(path):
    15         filepath=os.path.splitext(path)
    16         print filepath
    17         img_ext = ['.bmp','.jpeg','.gif','.psd','.png','.jpg']
    18         if filepath[1] in img_ext:
    19             os.rename(path,filepath[0]+'_gc'+filepath[1])
    20             i=i+1
    21     elif os.path.isdir(path):
    22         for x in os.listdir(path):
    23             change_name(os.path.join(path,x))
    24 
    25 change_name(Path2)  
    26 print "共修改了{}张图片".format(i)
  • 相关阅读:
    Mysql存储过程和函数
    python反编译chm文件并生成pdf文件
    python转换html到pdf文件
    python获取系统开机时间
    OpenSL ES: 利用OpenSL ES实现录音功能
    android: 根据文件uri 获取文件名
    Java: InputStream转化为byte数组
    Linux: 查看二进制文件
    Vim: 回到上次编辑的位置
    LayoutInflate: Avoid passing null as the view root
  • 原文地址:https://www.cnblogs.com/dongliping/p/11405460.html
Copyright © 2011-2022 走看看