Python 文件路径详解(os.path)

1 名称相关

修改中,请稍等。。。

1.1 获取基本名称:basename()

import os


def get_base_name(path):
    base_name = os.path.basename(path)
    # 根据路径,获取文件或目录名
    print(f'名称:{base_name}')
    return base_name


if __name__ == '__main__':
    file_path = r'C:\Users\Administrator\Desktop\Temp\1.txt'
    dir_path = r'C:\Users\Administrator\Desktop\Temp\1'
    get_base_name(file_path)  # 1.txt
    get_base_name(dir_path)  # 1

1.2 获取上级目录名:dirname()

import os


def get_abspath(path):
    abspath = os.path.dirname(path)
    # 根据路径,获取文件或目录的上级目录名
    print(f'上级目录名:{abspath}')
    return abspath


if __name__ == '__main__':
    file_path = r'C:\Users\Administrator\Desktop\Temp\1.txt'
    dir_path = r'C:\Users\Administrator\Desktop\Temp\1'
    get_abspath(file_path)  # C:\Users\Administrator\Desktop\Temp
    get_abspath(dir_path)  # C:\Users\Administrator\Desktop\Temp

1.3 获取绝对路径:abspath()

import os


def get_abspath(path):
    abspath = os.path.abspath(path)
    # 根据路径,获取文件或目录的绝对路径
    print(f'绝对路径:{abspath}')
    return abspath


if __name__ == '__main__':
    file_path = r'1.txt'
    dir_path = r'1'
    get_abspath(file_path)  # E:\01 Python 项目\FileDemo\1.txt
    get_abspath(dir_path)  # E:\01 Python 项目\FileDemo\1

1.4 获取共有最长路径:commonprefix()

import os


def get_commonprefix(path):
    commonprefix = os.path.commonprefix(path)
    # 获取共有的最长路径
    print(f'获取共有的最长路径:{commonprefix}')
    return commonprefix


if __name__ == '__main__':
    paths = ['/home/User/Desktop', '/home/User/Documents', '/home/User/Downloads']
    get_commonprefix(paths)  # /home/User/D

1.5 路径拼接:join()

import os

if __name__ == '__main__':
    base_path = r'C:\Users\Administrator\Desktop\Temp'
    # os.path.join(path1, path2, *)
    file_path = os.path.join(base_path, '1.txt')
    dir_path = os.path.join(base_path, '1')
    print(file_path)
    print(dir_path)
    print(os.path.join(base_path, '1', '2', '1.txt'))

1.6 路径切割:split()

import os

if __name__ == '__main__':
    # 以文件路径为例
    file_path = r'C:\Users\Administrator\Desktop\Temp\1.txt'
    name = os.path.split(file_path)

    dir_name = name[0]
    base_name = name[1]
    print(name)  # ('C:\\Users\\Administrator\\Desktop\\Temp', '1.txt')
    print(f'dir_name = {dir_name}, base_name = {base_name}')

    # 目录同理
    dir_path = r'C:\Users\Administrator\Desktop\Temp\1'

1.7 路径切割(文件后缀):splitext()

import os

if __name__ == '__main__':
    # 以文件路径为例
    file_path = r'C:\Users\Administrator\Desktop\Temp\1.txt'
    name = os.path.splitext(file_path)

    dir_name = name[0]
    base_name = name[1]
    print(name)  # ('C:\\Users\\Administrator\\Desktop\\Temp\\1', '.txt')
    print(f'dir_name = {dir_name}, base_name = {base_name}')

    # 目录同理
    dir_path = r'C:\Users\Administrator\Desktop\Temp\1'

1.8 目录遍历:walk()

含子目录:

import os

if __name__ == '__main__':
    # 本地桌面新建一个文件夹:Temp
    test_path = r"C:\Users\Administrator\Desktop\Temp"

    for dirPath, dirNames, fileNames in os.walk(test_path):
        print("文件路径  :", dirPath)
        print("文件夹名称:", dirNames)
        print("文件名称  :", fileNames)
        print()

不含子目录:

import os

if __name__ == '__main__':
    # 本地桌面新建一个目录:Temp
    test_path = r"C:\Users\Administrator\Desktop\Temp"

    for name in os.listdir(test_path):

        # 文件的绝对路径
        absolutePath = os.path.join(test_path, name)

        # 判断是 文件 还是 目录
        if os.path.isfile(absolutePath):
            print(f'文件: {name}')
        elif os.path.isdir(absolutePath):
            print(f'目录: {name}')

2 时间相关

2.1 返回创建日期:getctime()

import os
import time


def get_create_time(path):
    # 时间单位:时间戳
    create_time = os.path.getctime(path)
    print(create_time)
    # 时间单位:自定义时间字符串
    create_time_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(create_time))
    print(create_time_str)
    return create_time


if __name__ == '__main__':
    file_path = r'C:\Users\Administrator\Desktop\Temp\1.txt'
    dir_path = r'C:\Users\Administrator\Desktop\Temp\1'
    get_create_time(file_path)
    get_create_time(dir_path)

2.2 返回最近修改时间:getmtime()

import os
import time


def get_modify_time(path):
    # 时间单位:时间戳
    modify_time = os.path.getmtime(path)
    print(modify_time)
    # 时间单位:自定义时间字符串
    modify_time_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(modify_time))
    print(modify_time_str)
    return modify_time


if __name__ == '__main__':
    file_path = r'C:\Users\Administrator\Desktop\Temp\1.txt'
    dir_path = r'C:\Users\Administrator\Desktop\Temp\1'
    get_modify_time(file_path)
    get_modify_time(dir_path)

2.3 返回最近访问时间:getatime()

import os
import time


def get_access_time(path):
    # 时间单位:时间戳
    access_time = os.path.getatime(path)
    print(access_time)
    # 时间单位:自定义时间字符串
    access_time_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(access_time))
    print(access_time_str)
    return access_time


if __name__ == '__main__':
    file_path = r'C:\Users\Administrator\Desktop\Temp\1.txt'
    dir_path = r'C:\Users\Administrator\Desktop\Temp\1'
    get_access_time(file_path)
    get_access_time(dir_path)

在这里插入图片描述

3 判断条件

3.1 判断是否存在:exists()

  • 如果路径 path 存在,返回 True
  • 如果路径 path 不存在或损坏,返回 False
import os


def if_exists(path):
    abspath = os.path.exists(path)
    # 根据路径判断文件或目录是否存在
    print(f'文件或目录是否存在:{abspath}')
    return abspath


if __name__ == '__main__':
    file_path = r'C:\Users\Administrator\Desktop\Temp\1.txt'
    dir_path = r'C:\Users\Administrator\Desktop\Temp\2'
    if_exists(file_path)  # True
    if_exists(dir_path)  # False

3.2 判断是否存在(含损坏):lexists()

  • 路径存在则返回 True,路径损坏也返回 True
  • 路径不存在则返回 False
import os


def if_lexists(path):
    abspath = os.path.lexists(path)
    # 根据路径判断文件或目录是否存在
    print(f'文件或目录是否存在:{abspath}')
    return abspath


if __name__ == '__main__':
    file_path = r'C:\Users\Administrator\Desktop\Temp\1.txt'
    dir_path = r'C:\Users\Administrator\Desktop\Temp\2'
    if_lexists(file_path)  # True
    if_lexists(dir_path)  # False

3.3 判断是否为绝对路径:isabs()

import os


def is_abs(path):
    print(os.path.isabs(path))


if __name__ == '__main__':
    file_path = r'C:\Users\Administrator\Desktop\Temp\1.txt'
    dir_path = r'1'
    is_abs(file_path)  # True
    is_abs(dir_path)  # False

3.4 判断是否为文件:isfile()

import os


def is_file(path):
    print(os.path.isfile(path))


if __name__ == '__main__':
    file_path = r'C:\Users\Administrator\Desktop\Temp\1.txt'
    dir_path = r'C:\Users\Administrator\Desktop\Temp\1'
    is_file(file_path)  # True
    is_file(dir_path)  # False

3.5 判断是否为目录:isdir()

import os


def is_dir(path):
    print(os.path.isdir(path))


if __name__ == '__main__':
    file_path = r'C:\Users\Administrator\Desktop\Temp\1.txt'
    dir_path = r'C:\Users\Administrator\Desktop\Temp\1'
    is_dir(file_path)  # False
    is_dir(dir_path)  # True

3.6 判断是否相同:samefile()

import os


def is_same_file(path1, path2):
    print(os.path.samefile(path1, path2))


if __name__ == '__main__':
    file_path1 = r'C:\Users\Administrator\Desktop\Temp\1.txt'
    file_path2 = r'C:\Users\Administrator\Desktop\Temp\1.txt'
    dir_path1 = r'C:\Users\Administrator\Desktop\Temp\1'
    dir_path2 = r'C:\Users\Administrator\Desktop\Temp\1'
    is_same_file(file_path1, file_path2)  # True
    is_same_file(dir_path1, dir_path2)  # True
    # 注:若路径不存在,则报错

4 其它

4.1 转换用户:expanduser()

  • 把 path 中包含的 ~ 和 ~user 转换成用户目录
import os


def expand_user(_path):
    new_path = os.path.expanduser(_path)
    # 把 path 中包含的 ~ 和 ~user 转换成用户目录
    print(f'转换后的路径名:{new_path}')
    return new_path


if __name__ == '__main__':
    path = r"~\Documents\1.txt"
    expand_user(path)
    # C:\Users\Administrator\Documents\1.txt

4.2 转换环境变量:expandvars()

import os


def expand_user(_path):
    expand_var = os.path.expandvars(_path)
    # 环境变量转换
    print(f'转换后的值:{expand_var}')
    return expand_var


if __name__ == '__main__':
    path = r"$OS"
    # path = r"${OS}"  # 效果同上
    expand_user(path)  # Windows_NT

在这里插入图片描述

4.3 返回文件大小:getsize()

import os


def get_file_size(path):
    size = os.path.getsize(path)
    print(size)  # 字节


if __name__ == '__main__':
    file_path = r'C:\Users\Administrator\Desktop\Temp\1.txt'
    get_file_size(file_path)
    # 注:目录的大小 = 该目录下文件大小之和
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
Pythonos模块中的os.walk()函数是用来遍历文件夹的。它可以递归地遍历指定文件夹下的所有子文件夹和文件,并返回一个包含每个文件路径、子文件夹列表和文件列表的三元组的生成器。 而os.path.join()函数是用来连接路径的。它可以将多个路径组合成一个新的路径,并根据操作系统的不同自动添加正确的路径分隔符。这样可以方便地创建文件的绝对路径。 举个例子,如果我们有一个文件路径 `c:\Python`,并且文件夹中有一个名为 `a.txt` 的文件,我们可以使用os.path.join()函数将文件路径文件名连接起来,生成完整的文件路径 `'c:\\Python\\a.txt'`。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [Python os.walk() 方法遍历文件目录](https://blog.csdn.net/weixin_34567079/article/details/114911951)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *3* [如何用Python os.path.walk方法遍历搜索文件内容的操作详解_](https://blog.csdn.net/weixin_42216454/article/details/113963002)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鱼丸丶粗面

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值