Python之os模块

OS模块部分方法

os.getcwd()   # 获取当前工作路径
os.listdir(path)  # 返回path目录下所有文件
os.getenv()   # 获取一个环境变量
os.putenv()   # 设置一个环境变量
os.remove(path)  # 删除文件
os.system(command='')  # 执行一条shell命令
os.chdir(path)  # 改变工作目录到path

OS模块path方法

os.path.isfile()  # 判断是否是文件传入的参数是路径+文件名,不是文件名
os.path.isdir()   # 判断是否是目录,传入的参数是路径+文件名,不是文件名
os.path.exists()  # 判断路径是否存在
os.path.getsize(filename='')  # 获取文件大小
os.path.abspath(path='')  # 获得绝对路径
os.path.splitext(path='')  # 分离文件名与扩展名
os.path.split(path='')  # 分离路径和文件名
os.path.join(path, filename)  # 连接路径和文件名
os.path.basename(path)   # 返回文件名
os.path.dirname(path)    # 返回文件路径

例子:

返回某目录下的所有文件名
import os


def get_file(path):
    if os.path.exists(path):
        files = os.listdir(path)
        if len(files) == 0:
            print(path + "   目录为空")
        else:
            for file in files:
                if os.path.isfile(os.path.join(path, file)):
                    print(os.path.basename(file))
                elif os.path.isdir(os.path.join(path, file)):
                    get_file(file)
    else:
        print(path + "   路径不存在")


if __name__ == '__main__':
    path = ''
    get_file(path)
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值