Python os.path 查看,操作文件目录

取得 home 目录

例如我在我的本机上面
Input

os.path.expanduser("~")

Output

'/Users/edwin'

os.path.basename() 和 os.path.dirname() 的区别

  1. os.path.basename() 取得路径的尾部
  2. os.path.dirname() 取得路径的前部

Input

path = '/Users/edwin/develop/foo'
os.path.basename(path)
os.path.dirname(path)

Output

foo
/Users/edwin/develop/

os.walk()

os.walk(path) 可以遍历以path作为根节点的文件系统。对于需要取得文件目录信息的应用是非常有用的。这里会用一个实例来解释:
image.png

  1. 目的,取得除img文件夹之外所有的文件
  2. 代码
    # 建一个空List
    fname = []
    # 我们把**img**加到需要忽略的文件夹组中
    ignore_list = ['img']
    # 循环处理os.walk('~/docs')的结果
    for dirpath,dirnames,filenames in os.walk('~/docs'):
        if os.path.basename(dirpath) in ignore_list:
            # 清空dirnames 和 filenames, 如果取得文件夹的当前根目录在ignore_list 中
            dirnames[:] = []
            filenames[:] = []
        # 取filenames中的值
        for f in filenames:
            fname.append(os.path.join(dirpath, f))
  1. 输出
~/docs/api_m.md
~/docs/index.md
~/docs/kafka_cli.md
~/docs/kafka.md
~/docs/Legacy.md
~/docs/poslog.md
  1. 解释:
    os.walk(path) 会返回3个值,分别是dirpath: 正在遍历的文件目录的路径, dirnames:该文件目录下所有的文件夹, filenames:该文件目录下(此文件目录层)所有的文件.
    官方文档的解释:
    dirpath is a string, the path to the directory. dirnames is a list of the names of the subdirectories in dirpath (excluding '.' and '..'). filenames is a list of the names of the non-directory files in dirpath. Note that the names in the lists are just names, with no path components. To get a full path (which begins with top) to a file or directory in dirpath, do os.path.join(dirpath, name).
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值