python中os.path.dirname(__file__)的使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014157109/article/details/91354424

参考文章:
https://blog.csdn.net/u011760056/article/details/46969883
https://blog.csdn.net/renyuanxingxing/article/details/88830032
1.__file__表示当前.py文件的绝对路径:

print(__file__)
#结果
#/Users/Desktop/chapter9Exercises/BinaryIODemo.py

2.os.path模块下的常用函数:

import os
import time

# 获取绝对路径
print(os.path.abspath("abc.txt")) # G:\publish\codes\12\12.2\abc.txt
# 获取共同前缀
print(os.path.commonprefix(['/usr/lib', '/usr/local/lib'])) # /usr/l
# 获取共同路径
print(os.path.commonpath(['/usr/lib', '/usr/local/lib'])) # \usr
# 获取目录
print(os.path.dirname('abc/xyz/README.txt')) #abc/xyz
# 判断指定目录是否存在
print(os.path.exists('abc/xyz/README.txt')) # False
# 获取最近一次访问时间
print(time.ctime(os.path.getatime('os.path_test.py')))
# 获取最后一次修改时间
print(time.ctime(os.path.getmtime('os.path_test.py')))
# 获取创建时间
print(time.ctime(os.path.getctime('os.path_test.py')))
# 获取文件大小
print(os.path.getsize('os.path_test.py'))
# 判断是否为文件
print(os.path.isfile('os.path_test.py')) # True
# 判断是否为目录
print(os.path.isdir('os.path_test.py')) # False
# 判断是否为同一个文件
print(os.path.samefile('os.path_test.py', './os.path_test.py')) # True

注意:

os.path.exists(path)是判断路径path或者该路径下的文件是否存在,相当于os.path.isdir和os.path.isfile功能合集;

3.常见用法:

filepath = os.path.dirname(os.path.abspath(__file__))
print(filepath)#/Users/Desktop/chapter9Exercises
newpath = os.path.join(filepath,'demo.txt')
print(newpath)#/Users/brucejia/Desktop/chapter9Exercises/demo.txt

注意

使用os.path.join不用考虑分隔符“/”,""的问题,但是如果嫌用os.path.join麻烦,使用“+”直接拼接字符串,不要忘了分隔符。

如果在命令行执行os.path.abspath(_file_),则会引发异常NameError: name ‘file’ is not defined。

当"print os.path.dirname(_file_)"所在脚本是以相对路径被运行的, 那么将输出空目录。

猜你喜欢

转载自blog.csdn.net/u014157109/article/details/91354424