os.path的使用

os.path

1.返回当前目录

举个例子:

(1)给出一个目录名称,返回绝对路径

project_path = "Exercise"

path = os.path.dirname(os.path.abspath(project_path))

解析:

os.path.dirname(path)是返回文件路径的意思

os.path.abspath(path)是返回绝对路径的意思

(2)使用os.getcwd()也是返回当前路径

(3)os.path.dirname(os.path.realpath(__file__)) 或者os.path.split(os.path.realname(__file__))[0]

<1> os.path.realname(__file__):获取包含py文件名的完整路径
<2> os.path.dirname():去掉脚本的文件名,返回目录。
<3> os.path.dirname(os.path.realname(__file__)):指的是,该语句所在py文件的绝对路径,__file__为内置属性

2.返回父级目录

path = os.path.dirname(os.getcwd())

3.返回文件名

os.path.basename(path)

4.把路径分割成 dirname 和 basename,返回一个元组

os.path.split(path)

5.分割路径,返回路径名和文件扩展名的元组

os.path.splitext(path)

6.如果路径 path 存在,返回 True;如果路径 path 不存在,返回 False

os.path.exists(path)

7.返回最近访问时间(浮点型秒数)

os.path.getatime(path)

8.返回最近文件修改时间

os.path.getmtime(path)

9.返回文件 path 创建时间

os.path.getctime(path)

10.返回文件大小,如果文件不存在就返回错误

os.path.getsize(path)

11.判断是否为绝对路径

os.path.isabs(path)

12.判断路径是否为文件

os.path.isfile(path)

13.判断路径是否为目录

os.path.isdir(path)

14.判断路径是否为链接

os.path.islink(path)

15.判断路径是否为挂载点

os.path.ismount(path)

16.把目录和文件名合成一个路径

os.path.join(path1[, path2[, ...]])

17.转换path的大小写和斜杠

os.path.normcase(path)

18.规范path字符串形式

os.path.normpath(path)

19.判断目录或文件是否相同

os.path.samefile(path1, path2)

20.判断fp1和fp2是否指向同一文件

os.path.sameopenfile(fp1, fp2)

21.判断stat tuple stat1和stat2是否指向同一个文件

os.path.samestat(stat1, stat2)

22.获取指定目录下所有子目录、所有文件名

import os
def file_name(file_dir):
    for root, dirs, files in os.walk(file_dir):
        print('root_dir:', root)  # 当前目录路径
        print('sub_dirs:', dirs)  # 当前路径下所有子目录
        print('files:', files)  # 当前路径下所有非目录子文件


file_name('D:stock_data')

23.返回上上级目录

os.path.abspath(os.path.join(os.getcwd(), "../.."))
原文地址:https://www.cnblogs.com/yfacesclub/p/10386822.html