file path 相关

根据文件名来获取文件路径,要注意此脚本放在不同的位置运行会得到不同的结果
root是顶层文件,dirs是root下的子文件夹。

import os
base_dir = os.path.split(os.path.split(os.path.abspath(__file__))[0])[0]
#os.path.abspath(__file__) 返回的是当前文件的绝对路径, os.path.dirname(__file__) 返回的是当前文件所在文件夹的绝对路径,os.path.pardir是../ ,表示的是 上一层级目录,./ 表示的是目前所在的目录
def get_file_path(filename):
    for root, dirs, files in os.walk(base_dir):
        if filename in files:
            print('root is {}'.format(root))
            print('dirs is {}'.format(dirs))
            print('files is {}'.format(files))
            return os.path.join(root, filename)
# dirs是files上一层级的文件夹

os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))的解释
https://stackoverflow.com/questions/21005822/what-does-os-path-abspathos-path-joinos-path-dirname-file-os-path-pardir
https://www.geeksforgeeks.org/os-walk-python/

  1. abspath returns absolute path of a path

  2. join join to path strings

  3. dirname returns the directory of a file

  4. file refers to the script's file name

  5. pardir returns the representation of a parent directory in the OS (usually ..)

posted @ 2022-01-10 15:57  焰红火  阅读(130)  评论(0)    收藏  举报