Python的os模块常用方法

简单示例:

.abspath,.dirname

import os

#.abspath返回绝对路径:
#可以看出__file__表示了当前文件的path
print(os.path.abspath(__file__)) 作用: 获取当前脚本的完整路径

#.dirname返回文件路径:
#功能:去掉文件名,返回目录
BASE_DIR = os.path.dirname(os.path.abspath(__file__))

/home/master/pytorch/day_06/path.py
/home/master/pytorch/day_06

.join路径拼接

#.join路径拼接
train_dir = os.path.join(BASE_DIR, "train_data")
print(train_dir)
/home/master/pytorch/day_06/train_data

.exists路径

#.exists路径 判断文件/目录是否存在,返回为True 或者 False
print(os.path.exists(BASE_DIR))
true

os.walk:

在终端找到对应路径输入命令tree,查看文件夹目录树形图
在这里插入图片描述

os.walk:

os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])

参数

  • top – 根目录下的每一个文件夹(包含它自己), 产生3-元组 (dirpath, dirnames, filenames)【文件夹路径, 文件夹名字, 文件名】。
  • topdown --可选,为True或者没有指定, 一个目录的的3-元组将比它的任何子文件夹的3-元组先产生 (目录自上而下)。如果topdown为 False, 一个目录的3-元组将比它的任何子文件夹的3-元组后产生 (目录自下而上)。
  • onerror – 可选,是一个函数; 它调用时有一个参数, 一个OSError实例。报告这错误后,继续walk,或者抛出exception终止walk。
  • followlinks – 设置为 true,则通过软链接访问目录。

返回值

返回生成器

for root, dirs, files in os.walk(train_dir):
    print("root:",root)
    print("dirs:",dirs)
    print("files",files)
root: /home/master/pytorch/day_06/train_dir
dirs: ['1', '100']
files []

root: /home/master/pytorch/day_06/train_dir/1
dirs: []
files ['1.jpg', '2.jpg']

root: /home/master/pytorch/day_06/train_dir/100
dirs: []
files ['0.jpg', '1.jpg']

参考:

https://www.runoob.com/python/python-os-path.html

猜你喜欢

转载自blog.csdn.net/wahahaha116/article/details/122541841