python os.path常见方法

本文详细介绍了Python内置的os.path模块,包括常用的方法如abspath、basename、commonpath、commonprefix等,以及如何使用这些方法处理文件路径,例如获取文件的绝对路径、检查文件是否存在、获取文件的元数据信息等。通过实例展示了如何在实际操作中应用os.path模块。
摘要由CSDN通过智能技术生成

os.path()常见方法

Help on module ntpath:

NAME
    ntpath - Common pathname manipulations, WindowsNT/95 version.

DESCRIPTION
    Instead of importing this module directly, import os and refer to this
    module as os.path.

FUNCTIONS
    abspath(path)
        Return the absolute version of a path.
    
    basename(p)
        Returns the final component of a pathname
    
    commonpath(paths)
        Given a sequence of path names, returns the longest common sub-path.
    
    commonprefix(m)
        Given a list of pathnames, returns the longest common leading component
    
    dirname(p)
        Returns the directory component of a pathname
    
    exists(path)
        Test whether a path exists.  Returns False for broken symbolic links
    
    expanduser(path)
        Expand ~ and ~user constructs.
        
        If user or $HOME is unknown, do nothing.
    
    expandvars(path)
        Expand shell variables of the forms $var, ${var} and %var%.
        
        Unknown variables are left unchanged.
    
    getatime(filename)
        Return the last access time of a file, reported by os.stat().
    
    getctime(filename)
        Return the metadata change time of a file, reported by os.stat().
    
    getmtime(filename)
        Return the last modification time of a file, reported by os.stat().
    
    getsize(filename)
        Return the size of a file, reported by os.stat().
    
    isabs(s)
        Test whether a path is absolute
    
    isdir(s)
        Return true if the pathname refers to an existing directory.
    
    isfile(path)
        Test whether a path is a regular file
    
    islink(path)
        Test whether a path is a symbolic link.
        This will always return false for Windows prior to 6.0.
    
    ismount(path)
        Test whether a path is a mount point (a drive root, the root of a
        share, or a mounted volume)
    
    join(path, *paths)
        # Join two (or more) paths.
    
    lexists(path)
        Test whether a path exists.  Returns True for broken symbolic links
    
    normcase(s)
        Normalize case of pathname.
        
        Makes all characters lowercase and all slashes into backslashes.
    
    normpath(path)
        Normalize path, eliminating double slashes, etc.
    
    realpath(path)
    
    relpath(path, start=None)
        Return a relative version of a path
    
    samefile(f1, f2)
        Test whether two pathnames reference the same actual file or directory
        
        This is determined by the device number and i-node number and
        raises an exception if an os.stat() call on either pathname fails.
    
    sameopenfile(fp1, fp2)
        Test whether two open file objects reference the same file
    
    samestat(s1, s2)
        Test whether two stat buffers reference the same file
    
    split(p)
        Split a pathname.
        
        Return tuple (head, tail) where tail is everything after the final slash.
        Either part may be empty.
    
    splitdrive(p)
        Split a pathname into drive/UNC sharepoint and relative path specifiers.
        Returns a 2-tuple (drive_or_unc, path); either part may be empty.
        
        If you assign
            result = splitdrive(p)
        It is always true that:
            result[0] + result[1] == p
        
        If the path contained a drive letter, drive_or_unc will contain everything
        up to and including the colon.  e.g. splitdrive("c:/dir") returns ("c:", "/dir")
        
        If the path contained a UNC path, the drive_or_unc will contain the host name
        and share up to but not including the fourth directory separator character.
        e.g. splitdrive("//host/computer/dir") returns ("//host/computer", "/dir")
        
        Paths cannot contain both a drive letter and a UNC path.
    
    splitext(p)
        Split the extension from a pathname.
        
        Extension is everything from the last dot to the end, ignoring
        leading dots.  Returns "(root, ext)"; ext may be empty.

DATA
    __all__ = ['normcase', 'isabs', 'join', 'splitdrive', 'split', 'splite...
    altsep = '/'
    curdir = '.'
    defpath = r'.;C:\bin'
    devnull = 'nul'
    extsep = '.'
    pardir = '..'
    pathsep = ';'
    sep = r'\'
    supports_unicode_filenames = True

FILE
    d:\python3.8\lib\ntpath.py

Process finished with exit code 0
import yaml
import os

#help(yaml)
#help(os.path)
#os.path.abspath('main.yaml')  #获取main.yaml的绝对路径
print(os.path.abspath('main.yaml'))   #D:\文件存储\日常练习编写\file_IO\parse_yaml\main.yaml

#os.path.basename('D:\文件存储\日常练习编写\file_IO\parse_yaml\main.yaml')  #获取main.yaml的相对路径
print(os.path.basename('main.yaml'))    #main.yaml
print(os.path.basename('D:\文件存储\日常练习编写\file_IO\parse_yaml\main.yaml'))   #main.yaml

#os.path.commonpath(dir_list) #返回list中所有path共有的最长路径,合法的
dir_list = ['D:\文件存储\日常练习编写\file_IO\parse_yaml\main.yaml','D:\文件存储\日常练习编写\test_argparse.py']
print(os.path.commonpath(dir_list))   #D:\文件存储

#os.path. commonprefix(dir_list) 返回list中所有path共有的前缀,有可能不是路径,非法的
print(os.path. commonprefix(dir_list))   #D:\文件存储\日常练习编写
#os.path.dirname(__file__) 返回当前文件的路径,不包含当前文件名
#help(os.path.dirname(''))
print(os.path.dirname(__file__))  #D:/文件存储/日常练习编写/file_IO/parse_yaml

#os.path.exists('f')  路径存在为True,False;必须是linux路径
print(os.path.exists('f'))
print(os.path.exists('D:/文件存储/日常练习编写/file_IO/parse_yaml/REAAME.md'))
print(os.path.exists('D:\文件存储\日常练习编写\file_IO\parse_yaml\main.yaml'))

#os.path.getatime('main.yaml')   返回由os.stat()报告的文件的最后访问时间。
print(os.path.getatime('main.yaml'))   #1624115120.6756277

#os.path.getctime('main.yaml')   返回由os.stat()报告的文件的元数据更改时间。
"""
mtime指的是上次更改文件内容的时间.这可以通过各种方式在unix系统上进行更改.通常,从备份还原文件时,会更改mtime以指示在进行备份之前上次更改内容的时间.
ctime表示最后一次改变inode.这不能改变.在上面的备份示例中,ctime仍将反映文件恢复的时间.此外,更改文件权限等内容时会更新ctime.
"""
print(os.path.getctime('main.yaml'))    #1624115120.6706402

#os.path.getmtime('main.yaml')  返回由os.stat()报告的文件的最后一次修改时间。
print(os.path.getmtime('main.yaml'))

#os.path.getsize('main.yaml')  返回由os.stat()报告的文件大小。 以字节为单位
print(os.path.getsize('main.yaml'))

#os.path.isabs('') 判断文件路径是否完整,完整为True.不完整为False
print(os.path.isabs('D:\文件存储\日常练习编写\file_IO\parse_yaml\main.yaml'))  #True
print(os.path.isabs('main.yaml'))  #False

#os.path.isdir('')  判断是否为路径,是返回True ,不是返回False,不区分linux还是windowss
print(os.path.isdir('main.yaml')) #False
print(os.path.isdir('D:\文件存储\日常练习编写\test_sys.py')) #False
print(os.path.isdir('D:\文件存储\日常练习编写'))  #True
print(os.path.isdir('F:\文件存储\日常练习编写\test_sys.py')) #False
print(os.path.isdir('D:/文件存储/日常练习编写/test_sys.py'))#False
print(os.path.isdir('D:/文件存储/日常练习编写/')) #True

#os.path.isfile('') 判断是否为文件,是返回True ,不是返回False,区分linux和Windows,不识别Windows绝对路径及相对路径,只识别单个文件
print(os.path.isfile('main.yaml')) #True
print(os.path.isfile('parse_yaml\main.yaml')) #False
print(os.path.isfile('D:\文件存储\日常练习编写\test_sys.py')) #False
print(os.path.isfile('D:\文件存储\日常练习编写'))  #False
print(os.path.isfile('F:\文件存储\日常练习编写\test_sys.py')) #False
print(os.path.isfile('D:/文件存储/日常练习编写/test_sys.py'))#True
print(os.path.isfile('D:/文件存储/日常练习编写/')) #False

#os.path.islink('')  判断是否为软链接(符号链接),是返回True ,不是返回False,对于6.0之前的Windows,这将始终返回false。
print(os.path.islink('main.yaml')) #False

#os.path.ismount('')  判断是否为磁盘挂载点。是返回True ,不是返回False,
print(os.path.ismount('D:'))#False

#os.path.join(path1,path2)  path1和path2拼接,path1在前
print(os.path.join('main.yaml','D:\文件存储\日常练习编写\/file_IO\parse_yaml'))  #D:\文件存储\日常练习编写\/file_IO\parse_yaml
print(os.path.join('parse_yaml\main.yaml','D:\文件存储\日常练习编写\/file_IO'))  #D:\文件存储\日常练习编写\/file_IO
print(os.path.join('D:\文件存储\日常练习编写\/file_IO\parse_yaml','main.yaml'))  #D:\文件存储\日常练习编写\/file_IO\parse_yaml\main.yaml

#os.path.lexists() 测试路径是否存在。对于中断的符号链接返回True
print(os.path.lexists('main.yaml'))  #True

#os.path.normcase('') 规范路径的大小写,使所有字符小写,所有斜杠为反斜杠
print(os.path.normcase('D:\文件存储\日常练习编写\/file_IO\parse_yaml\main.yaml')) #d:\文件存储\日常练习编写\\file_io\parse_yaml\main.yaml

#os.path.normpath()  规范化路径,消除双斜线等。
print(os.path.normpath('D:\文件存储\日常练习编写\/file_IO\parse_yaml\main.yaml'))

#os.path.realpath(__file__)  获取当前执行脚本的绝对路径
print(os.path.realpath(__file__))  #D:\文件存储\日常练习编写\file_IO\parse_yaml\parse_yaml_01.py

#os.path.relpath() 返回当前文件所在路径与目标文件相比的相对路径
print(os.path.relpath('D:\文件存储\日常练习编写\/file_IO\parse_yaml\main.yaml',start=None))
print(os.path.relpath('D:\文件存储\日常练习编写\/file_IO\parse_yaml\main.yaml','parse_yaml'))
print(os.path.relpath('D:\文件存储\日常练习编写\/file_IO\parse_yaml\main.yaml','file_IO'))
print(os.path.relpath('D:\文件存储\日常练习编写\/test_argparse.py'))

#os.path.samefile() 测试两个路径名是否引用相同的实际文件或目录
print(os.path.samefile('main.yaml','D:\文件存储\日常练习编写\/file_IO\parse_yaml\main.yaml')) #True
print(os.path.samefile('D:\文件存储\日常练习编写\/main.yaml','D:\文件存储\日常练习编写\/file_IO\parse_yaml\main.yaml')) #False  复制文件更换路径就不是了

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值