python基础:os.path的相关操作

#-*-coding:utf-8-*-
'''
@author: wzg16
@software: pycharm
@file: os_lsdir_test.py
@time: 6/19/19 2:49 AM
@funcion:
'''
"""
os:operating system,程序所在的操作系统
"""
import os

# 返回当前文件路径
# 任何一个文件都会有一个__file__属性,代表当前文件的路径,但不能确定是绝对路径还是相对路径
print(__file__)

# 返回当前文件的绝对路径
current_path = os.path.abspath(__file__)
print(current_path)

## 返回当前文件所在目录
current_dir = os.path.dirname(os.path.abspath(__file__))
print(current_dir)

## 返回文件名
filename = os.path.basename(os.path.abspath(__file__))
print(filename)

## 判断路径是否存在
print(os.path.exists(os.path.abspath(__file__)))

## 判断是否为文件 #只识别后缀,不判断文件是否存在
print(os.path.isfile(current_dir))
print(os.path.isfile(filename))

## 判断路径是否为目录 #同时判断目录是否存在,需要路径是绝对路径
print(os.path.isdir(current_dir))
print(os.path.isdir(current_path))
print(os.path.isdir("/Desktop/test/os_test"))

## 路径合并--把目录路径和文件路径合并
combined_path = os.path.join(current_dir,filename)
print(combined_path)
print(os.path.exists(combined_path))

## 路径分割 -- 主要将“目录”与“文件名”分开,返回一个tuple(元组)
print(os.path.split(current_path))

## 路径分割 -- 主要将“目录+文件名”与“文件名后缀(带'.')”分开,返回一个tuple(元组)
# 第二个元素是文件名后缀
print(os.path.splitext(current_path))




"""
os.walk 游走方式:
        root 游走方式:1)当前文件夹  2)随机选择当前文件夹下的子文件夹,深度优先。
             备注:‘.idea’是一种特殊的文件夹,由Pycharm等IDE自动生成,内含".xml"文件.
                   该文件/文件夹用于存储当前项目的配置信息、历史记录等。与当前项目是否
                   正常执行无任何关系。如果在遍历文件夹时,需要考虑排除这种不需要的情况。
             
        dirs 游走方式:以列表形式返回当前root下的所有子文件夹的名称。无序。
        
        files 游走方式:以列表形式返回当前root下的所有文件的名称。无序。

"""
print("\n#################################\n")
for root,dirs,files in os.walk("/home/wzg16/Desktop/test/os_test"):
    print('---->root:',root)
    print('---->dirs:', dirs)
    print('---->files:', files)

    print('#############################################')




"""
os.path.walk()  
在python3.4以后已经被取消使用
"""
path = "/home/wzg16/Desktop/test/os_test"
def path_func(args,dirname,names):
    print('args=',args)
    print('dirnames=',dirname)
    print('names=',names)

# os.path.walk(path,path_func,())

print(dir(os.path))

print("\n#############--help(os.path)--######################")
help(os.path)## 内置了print函数

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值