Python 的OS 模块(一)

使用python编写脚本的时候最常用的就是os 模块啦,今天总结下os模块常用的一些方法
1. 得到当前的工作目录 : os.getcwd()
2. 返回指定目录下的所有文件和目录名: os.listdir()
3. 删除文件: os.remove()
4. 删除多个目录:os.removedirs()
5. 检查是否是文件: os.path.isfile()
6. 检查是否是目录: os.path.isdir()
7. 判断是否是绝对路径:os.path.isabs()
8. 检查路径是否存在: os.path.exists()
9. 分离扩展名:os.path.splitext() #如果要返回后缀,取索引为1的值
10. 获取路径名:os.path.dirname()
11. 获取文件名:os.path.basename()
举例:

#!/usr/bin/python
#-*- coding:UTF-8 -*-
import os

test_dir = 'D:\\Python27\\2015-example\\FileDir\\test\\'

current_dir = os.getcwd()
print 'current dir is :',current_dir
base_name = os.path.basename(current_dir)
print 'basename is :',base_name
dir_name = os.path.dirname(current_dir)
print 'dirname is :',dir_name

def del_file(test_dir):
    if(os.path.exists(test_dir) and os.path.isdir(test_dir)): # is dir and exist
        files = os.listdir(test_dir)
        if files:
            for f in files:
                if os.path.isfile(os.path.join(test_dir,f)): # is file
                    print test_dir,' is not null,now will delete ',f
                    ext_name = os.path.splitext(os.path.join(test_dir,f))#split ext
                    print 'ext_name is ',ext_name[1]
                    os.remove(os.path.join(test_dir,f))# delete file
                else:
                    del_file(os.path.join(test_dir,i))
        #null dir
        else:
            print '*****this is a null dir'

if __name__ == '__main__':

    del_file(test_dir)

运行结果:
这里写图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Pythonos模块是一个用于处理文件系统的常用模块。它提供了各种方法来处理文件和目录。在Python中,os模块是跨平台的,这意味着你不需要关心操作系统使用了什么模块os模块会自动选择并调用正确的模块。 通过使用os模块,你可以轻松地获取当前工作目录(即当前Python脚本所在的目录)的路径,使用`os.getcwd()`方法即可实现。 此外,os模块还提供了许多其他有用的方法,例如`os.listdir()`方法可以列出指定路径下的所有文件和目录。你只需要提供一个路径作为参数,比如`os.listdir("C:Users黄伟Desktoppublishos模块 est_os模块")`就可以获取该路径下的所有文件和目录列表。 总结来说,Pythonos模块是一个十分有用的模块,它提供了处理文件系统的功能,包括获取当前工作目录和列出指定路径下的文件和目录等功能。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Python OS 模块](https://blog.csdn.net/hj1993/article/details/129431726)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [Python模块——os模块详解](https://blog.csdn.net/qq_46416934/article/details/125241212)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值