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)
    # 注:目录的大小 = 该目录下文件大小之和
Python中,获取文件路径可以通过多种方式,这里介绍几种常见的方法: 1. 使用`input()`函数直接从用户那里获取路径: ```python file_path = input("请输入文件路径:") ``` 2. 使用`os.path`模块中的`expanduser()`函数来处理用户主目录的相对路径,使其变为绝对路径: ```python import os.path file_path = os.path.expanduser('~/Desktop/myfile.txt') ``` 3. 使用`pathlib`模块的`Path`类来处理文件路径。`pathlib`提供了面向对象的方式来处理文件系统路径: ```python from pathlib import Path file_path = Path.home() / 'Desktop' / 'myfile.txt' ``` 4. 使用命令行参数获取路径,例如使用`argparse`模块解析命令行参数: ```python import argparse parser = argparse.ArgumentParser(description="获取文件路径示例") parser.add_argument('file_path', type=str, help='请输入文件路径') args = parser.parse_args() file_path = args.file_path ``` 5. 如果在编写一个图形用户界面(GUI)程序,可以使用GUI组件如Tkinter的文件对话框来让用户选择文件: ```python import tkinter as tk from tkinter import filedialog root = tk.Tk() root.withdraw() # 隐藏主窗口 file_path = filedialog.askopenfilename(title="选择文件", filetypes=[("所有文件", "*.*"), ("文本文件", "*.txt")]) print("您选择的文件是:", file_path) ``` 使用以上方法之一即可获取用户输入的文件路径,具体选择哪一种方法取决于你的应用程序需要和上下文环境。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

鱼丸丶粗面

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

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

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

打赏作者

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

抵扣说明:

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

余额充值