Common methods of Python's os module

Simple example:

.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 path splicing

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

.existspath

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

os.walk:

Find the corresponding path in the terminal and enter the command tree to view the tree diagram of the folder directory
insert image description here

os.walk:

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

parameter

  • top - For each folder (including itself) under the root directory, generate a 3-tuple (dirpath, dirnames, filenames) [folder path, folder name, file name].
  • topdown -- optional, if True or not specified, a directory's 3-tuple will be generated before any of its subfolders' 3-tuples (directories top down). If topdown is False, a directory's 3-tuple will be generated after any of its subfolders' 3-tuples (directories bottom up).
  • onerror – optional, is a function; it is called with one argument, an OSError instance. After reporting this error, continue the walk, or throw an exception to terminate the walk.
  • followlinks – set to true, then visit the directory through soft links.

return value

return builder

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']

reference:

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

Guess you like

Origin blog.csdn.net/wahahaha116/article/details/122541841