python文件名获取文件路径

如题所述

第1个回答  2022-12-11

概述

使用os.path.abspath()函数来获取文件绝对路径

解析

文件目录结构如下:

假设app.py中想读取config.ini文件的内容,首先app.py需要知道config.ini的文件路径,从目录结构上可以看出,config.ini与app.py的父目录同级,也就是获取到app.py父目录(bin文件夹的路径)的父目录(config文件夹路径)的绝对路径再拼上config.ini文件名就能获取到config.ini文件:

首先,在app.py中测试一下:

import os

def load_file():

# 获取当前文件路径

current_path = os.path.abspath(__file__)

# 获取当前文件的父目录

father_path = os.path.abspath(os.path.dirname(current_path) + os.path.sep + ".")

# config.ini文件路径,获取当前目录的父目录的父目录与congig.ini拼接

config_file_path=os.path.join(os.path.abspath(os.path.dirname(current_path) + os.path.sep + ".."),'config.ini')

print('当前目录:' + current_path)

print('当前父目录:' + father_path)

print('config.ini路径:' + config_file_path)

load_file()

#out:

从结果中可以看到一切都正常,没有什么问题,假如现在需要从main.py中执行app.py的load_file()方法呢?

来测试一下:

main.py(处于同级目录):

from bin.app import load_file

if __name__=='__main__':

load_file()

#out:

可以看到,获取的路径是完全没有问题的

拓展内容

python os.path 常用模块介绍

os.path.abspath(path) 返回path规范化的绝对路径(但这个路径不一定是真实的路径),如果path仅是一个文件名,使用该函数后返回的路径是当前工作目录路径连接改文件名后所组成的新的路径名。

>>> import os.path

>>> os.path.abspath("a.py")

'C:\\Users\\Administrator\\a.py'

os.path.split(path) 将path分割成目录和文件名二元组返回

>>> os.path.split("C:\\Users\\Administrator\\a.py")
('C:\\Users\\Administrator', 'a.py')

os.path.dirname(path) 返回path的目录,其实就是os.path.split(path)的第一个元素

>>> os.path.dirname("C:\\Users\\Administrator\\a.py")
'C:\\Users\\Administrator'

os.path.basename(path) 返回path最后的文件名。如果path以/或\结尾,就会返回空值。即os.path.split(path)的第二个元素。

>>> os.path.basename("C:\\Users\\Administrator\\a.py")

'a.py'

os.path.commonprefix(list) 返回list中所有path共有的最长的路径,从左向右,相同字符。

os.path.exists(path) 如果path存在,返回True;如果path不存在,返回False。

os.path.isabs(path) 如果path是绝对路径,返回True。

os.path.normpath(path) 规范path字符串形式(规范文件路径)

os.path.isfile(path) 判断路径是否为文件,是返回True,否则返回False

os.path.isdir(path) 如果path是一个存在的目录,返回True,否则返货False。

os.path.islink(path) 是否是链接;但如果系统不支持链接,则返回False。

相似回答