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/
-
abspath returns absolute path of a path
-
join join to path strings
-
dirname returns the directory of a file
-
file refers to the script's file name
-
pardir returns the representation of a parent directory in the OS (usually ..)

浙公网安备 33010602011771号