Python 常用模块(三):os.path模块

一、os.path模块介绍

os 模块是 Python 内置的与操作系统功能和文件系统相关的模块。该模块的子模块 os.path 是专门用于进行路径操作的模块。常用的路径操作主要有判断目录是否存在、创建目录、删除目录和遍历目录等。

Type:        module
String form: <module 'ntpath' from 'F:\\dev_tools\\python\\python310\\lib\\ntpath.py'>
File:        f:\dev_tools\python\python310\lib\ntpath.py
Docstring:
Common pathname manipulations, WindowsNT/95 version.

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

os 模块和它的子模块 os.path 都属于内置模块,不需要安装,直接导入即可使用。在 Python 程序中,使用 import 语句导入 os 模块后,既可以使用 os 模块提供的属性和方法,又可以使用 os.path 模块提供的属性和方法。导入 os 模块的代码如下:

import os  # 导入 os 模块后,也可以使用其子模块os.path

如果在程序中,只涉及到 os.path 模块的内容,也可以直接导入 os.path,代码如下:

import os.path

使用上面的代码导入 os.path 模块后,就可以使用该模块提供的属性和方法了。如果不确定该模块都提供了哪些属性和方法,可以使用 Python 的内置函数 dir() 获取其全部方法列表,代码如下:

In [4]: import os.path

In [5]: dir(os.path)
Out[5]:
['_LCMAP_LOWERCASE',
 '_LCMapStringEx',
 '_LOCALE_NAME_INVARIANT',
 '__all__',
 '__builtins__',
 '__cached__',
 '__doc__',
 '__file__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__',
 '_abspath_fallback',
 '_get_bothseps',
 '_getfinalpathname',
 '_getfinalpathname_nonstrict',
 '_getfullpathname',
 '_getvolumepathname',
 '_nt_readlink',
 '_readlink_deep',
 'abspath',
 'altsep',
 'basename',
 'commonpath',
 'commonprefix',
 'curdir',
 'defpath',
 'devnull',
 'dirname',
 'exists',
 'expanduser',
 'expandvars',
 'extsep',
 'genericpath',
 'getatime',
 'getctime',
 'getmtime',
 'getsize',
 'isabs',
 'isdir',
 'isfile',
 'islink',
 'ismount',
 'join',
 'lexists',
 'normcase',
 'normpath',
 'os',
 'pardir',
 'pathsep',
 'realpath',
 'relpath',
 'samefile',
 'sameopenfile',
 'samestat',
 'sep',
 'split',
 'splitdrive',
 'splitext',
 'stat',
 'supports_unicode_filenames',
 'sys']

二、常用方法

2.1 join()方法——拼接路径

join() 方法用于将两个或者多个路径拼接到一起组成一个新的路径。语法格式如下:

In [6]: os.path.join?
Signature: os.path.join(path, *paths)
Docstring: <no docstring>
File:      f:\dev_tools\python\python310\lib\ntpath.py
Type:      function
参数说明: 
1.path: 表示要拼接的文件路径
2.*paths: 表示要拼接的多个文件路径,这些路径间使用逗号进行分隔。
如果在要拼接的路径中,没有一个绝对路径,那么最后拼接出来的将是一个相对路径。
3.返回值: 拼接后的路径。
ps: 使用os.path.join() 函数拼接路径时,并不会检测该路径是否真实存在。

示例:

In [7]: # 拼接绝对路径和相对路径

In [8]: os.path.join(r'D:\Code\dream', 'PythonStudy/base/day06-文件IO和序列化/pathlib_demo.py')
Out[8]: 'D:\\Code\\dream\\PythonStudy/base/day06-文件IO和序列化/pathlib_demo.py'

In [9]: # 拼接多个绝对路径

In [10]: os.path.join(r'C:\Users\amoxiang',r'D:\Code\dream', 'PythonStudy', r'D:\', 'demo')
  Cell In[10], line 1
    os.path.join(r'C:\Users\amoxiang',r'D:\Code\dream', 'PythonStudy', r'D:\', 'demo')
                                                                                    ^
SyntaxError: unterminated string literal (detected at line 1)

# 如果要拼接的路径中,存在多个绝对路径,那么按从左到右顺序,以最后一次出现的绝对路径为准,
# 并且该路径之前的参数都将被忽略,代码如下: 
In [11]: os.path.join(r'C:\Users\amoxiang',r'D:\Code\dream', 'PythonStudy', r'D:/', 'demo' )
Out[11]: 'D:/demo'

把两个路径拼接为一个路径时,不要直接使用字符串拼接,而是使用 os.path.join() 方法,这样可以正确处理不同操作系统的路径分隔符。

2.2 exists()方法——判断路径是否存在(准确)

exists() 方法用于判断路径(文件或目录)是否存在,如果存在则返回 True ;不存在则返回 False。如果是断开的符号链接,也返回 False。语法格式如下:

In [13]: os.path.exists?
Signature: os.path.exists(path)
Docstring: Test whether a path exists.  Returns False for broken symbolic links
File:      f:\dev_tools\python\python310\lib\genericpath.py
Type:      function
参数说明: 
1.path: 表示要判断的路径,可以采用绝对路径,也可以采用相对路径。
2.返回值: 如果给定的路径存在,则返回True,否则返回False。
注意: 在使用 exists() 方法时,如果某些平台未授予 os.stat() 对所请求文件有执行的权限,即使路径真实存在,
使用该方法也会返回 False

示例:

In [14]: # 1.判断文件是否存在

In [15]: os.path.exists(r'D:\Code\dream\PythonStudy\base\day06-文件IO和序列化\pathlib_demo.py')
Out[15]: True

In [16]: # 2.判断目录是否存在

In [17]: os.path.exists(r'D:\Code\dream\PythonStudy\base/')
Out[17]: True

In [18]: os.path.exists('D:/Code/dream/PythonStudy/base/')
Out[18]: True

2.3 split()方法——分割路径名

split() 方法用于从一个路径中分割出目录和文件名。语法格式如下:

In [19]: os.path.split?
Signature: os.path.split(p)
Docstring:
Split a pathname.

Return tuple (head, tail) where tail is everything after the final slash.
Either part may be empty.
File:      f:\dev_tools\python\python310\lib\ntpath.py
Type:      function
参数说明: 
1.p: 表示要分割的路径,可以采用绝对路径,也可以采用相对路径。
2.返回值: 返回一个元组,与(os.path.dirname(),os.path.basename()) 返回的元组相同。
如果指定的是一个相对路径,并且以斜杠结尾,则返回的元组的第二个元素为空。

示例:

In [20]: # 1.从不同路径中分割目录和文件名

# # 分割绝对路径
In [21]: os.path.split(r'D:\Code\dream\PythonStudy\base\day06-文件IO和序列化\pathlib_demo.py')
Out[21]: ('D:\\Code\\dream\\PythonStudy\\base\\day06-文件IO和序列化', 'pathlib_demo.py')

# 分割绝对路径
In [22]: os.path.split('D:/Code\dream/PythonStudy/base/day06-文件IO和序列化')
Out[22]: ('D:/Code\\dream/PythonStudy/base', 'day06-文件IO和序列化')

In [23]: os.path.split('D:/Code/dream/PythonStudy/base/day06-文件IO和序列化')
Out[23]: ('D:/Code/dream/PythonStudy/base', 'day06-文件IO和序列化')

In [24]: os.path.split('dream/PythonStudy/base/day06-文件IO和序列化')
Out[24]: ('dream/PythonStudy/base', 'day06-文件IO和序列化')

# # 分割相对路径
In [25]: os.path.split('/dream/PythonStudy/base/day06-文件IO和序列化')
Out[25]: ('/dream/PythonStudy/base', 'day06-文件IO和序列化')

In [29]: dirname, filename = os.path.split(r'D:\Code\dream/test.py')

In [30]: dirname
Out[30]: 'D:\\Code\\dream'

In [31]: filename
Out[31]: 'test.py'

2.4 splitdrive()方法——分割驱动器和目录

splitdrive() 方法用于从一个路径中分割驱动器和目录,在不使用驱动器的操作系统中,返回元组的第一个元素始终为空字符串。语法格式如下:

In [32]: os.path.splitdrive?
Signature: os.path.splitdrive(p)
Docstring:
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.
File:      f:\dev_tools\python\python310\lib\ntpath.py
Type:      function
参数说明: 
1.path: 表示要分割的路径,可以采用绝对路径,也可以采用相对路径。
2.返回值: 返回一个元组,它的第一个元素为字符串表示的驱动器名,第二个元素为字符串表示的目录。
如果指定的路径为相对路径,则返回元组的第一个元素为空字符串。

示例:

# linux下
[root@VM-16-6-centos ~]# python3
Python 3.8.10 (default, Jun 28 2024, 03:45:43) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os.path
>>> os.path.splitdrive('/AntiSpider/templates/index.html')
('', '/AntiSpider/templates/index.html')
>>> os.path.splitdrive('templates/index.html')
('', 'templates/index.html')

# windows下
In [33]: # 1.从不同路径中分割驱动器和目录

In [34]: os.path.splitdrive(r'D:\Code\dream/test.py')
Out[34]: ('D:', '\\Code\\dream/test.py')

In [35]: os.path.splitdrive('Code/dream/test.py')
Out[35]: ('', 'Code/dream/test.py')

2.5 splitext()方法——分割文件名和扩展名

splitext() 方法用于从一个路径中分割基本文件名和扩展名。语法格式如下:

In [37]: os.path.splitext?
Signature: os.path.splitext(p)
Docstring:
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.
File:      f:\dev_tools\python\python310\lib\ntpath.py
Type:      function
参数说明: 
1.p: 表示要分割的路径,可以采用绝对路径,也可以采用相对路径。
2.返回值: 返回一个元组,它的第一个元素为字符串表示的基本文件名(路径中除扩展名以外的部分),
第二个元素为字符串表示的扩展名(包括"."号)。如果指定的路径中不包括扩展名,则返回元组的第二个元素为空字符串。

示例:

In [38]: # 1.从不同路径中分割文件名和扩展名

In [39]: os.path.splitext('Code/dream/test.py')
Out[39]: ('Code/dream/test', '.py')

In [40]: os.path.splitext(r'D:\Code\dream\PythonStudy\base\day06-文件IO和序列化\pathlib_demo.py')
Out[40]: ('D:\\Code\\dream\\PythonStudy\\base\\day06-文件IO和序列化\\pathlib_demo', '.py')

In [41]: os.path.splitext('D:/Code/dream/PythonStudy/base/day06-文件IO和序列化')
Out[41]: ('D:/Code/dream/PythonStudy/base/day06-文件IO和序列化', '')

2.6 dirname()方法——获取路径中的目录

dirname() 方法用于从一个路径中提取目录。它相当于使用 os.path.split() 方法分割路径后,得到的第一个元素。语法格式如下:

In [42]: os.path.dirname?
Signature: os.path.dirname(p)
Docstring: Returns the directory component of a pathname
File:      f:\dev_tools\python\python310\lib\ntpath.py
Type:      function
参数说明: 
1.p: 表示要提取目录的路径。
2.返回值:返回提取后的目录。

示例:

In [43]: # 1.从绝对路径中提取目录

In [44]: os.path.dirname('d:/code/dream/test.py')
Out[44]: 'd:/code/dream'

In [45]: # 2.从相对路径中提取目录

In [46]: os.path.dirname('dream/test.py')
Out[46]: 'dream'

In [47]: os.path.dirname('code/dream/test.py')
Out[47]: 'code/dream'

# 打印父目录
# path1 = 'D:/Code/dream/PythonStudy/base/day06-文件IO和序列化/os_path_demo.py'
path1 = 'dream/PythonStudy/base/day06-文件IO和序列化/os_path_demo.py'
while path1 != os.path.dirname(path1):
    path1 = os.path.dirname(path1)
    print(path1)

2.7 basename()方法——从一个路径中提取文件名

basename() 方法用于从一个路径中提取文件名。当指定的路径是一个不包括文件名的路径(如 c:/temp/)时,返回空字符串。语法格式如下:

In [48]: os.path.basename?
Signature: os.path.basename(p)
Docstring: Returns the final component of a pathname
File:      f:\dev_tools\python\python310\lib\ntpath.py
Type:      function
参数说明: 
1.p: 表示要提取文件名的路径。
2.返回值: 返回提取后的文件名。

示例:

In [49]: # 1.从相对路径中提取文件名

In [50]: os.path.basename('code/dream/test.py')
Out[50]: 'test.py'

In [51]: # 2.从绝对路径中提取文件名

In [52]: path1 = 'e:/demo/test.txt'
    ...:
    ...: path2 = 'e:/demo'

In [53]: os.path.basename(path1)
Out[53]: 'test.txt'

In [54]: os.path.basename(path2)
Out[54]: 'demo'

In [55]: # path2 中的demo 被当作了文件名来处理。如果path 以/或\结尾,那么就会返回空值

In [56]: path2 = 'e:/demo/'

In [57]: os.path.basename(path2)
Out[57]: ''

2.8 abspath()方法——获取绝对路径

abspath() 方法用于返回文件或者目录的绝对路径。语法格式如下:

In [58]: os.path.abspath?
Signature: os.path.abspath(path)
Docstring: Return the absolute version of a path.
File:      f:\dev_tools\python\python310\lib\ntpath.py
Type:      function
参数说明: 
1.path: 表示要获取绝对路径的相对路径,可以是文件也可以是目录。
2.返回值: 返回获取到的绝对路径。
3.说明: 绝对路径是指在使用文件时指定文件的实际路径。它不依赖于当前工作目录。
注意:abspath() 方法在获取实际路径时,并不会检查路径是否真实存在,只是把当前文件目录与abspath()方法给定的路径进行拼接。

示例:

# -*- coding: utf-8 -*-
# @Time    : 2024-09-17 6:32
# @Author  : AmoXiang
# @File: os_path_demo.py
# @Software: PyCharm
# @Blog: https://blog.csdn.net/xw1680

import os.path

# D:\Code\dream\PythonStudy\base\day06-文件IO和序列化\os_path_demo.py
print(os.path.abspath(os.path.basename(__file__)))
print(os.path.basename(__file__))  # os_path_demo.py

# D:\Code\dream\PythonStudy\base\day06-文件IO和序列化\demo\message.txt
print(os.path.abspath(r'demo\message.txt'))  # 打印绝对路径
# D:\Code\dream\PythonStudy\base\day06-文件IO和序列化
print(os.path.abspath(''))  # 打印绝对路径 
# D:\Code\dream\PythonStudy\base\day06-文件IO和序列化
print(os.path.abspath('.'))  # 打印绝对路径

2.9 isf ile()方法——判断是否为普通文件

isfile() 方法用于判断是否为普通文件。语法格式如下:

In [65]: os.path.isfile?
Signature: os.path.isfile(path)
Docstring: Test whether a path is a regular file
File:      f:\dev_tools\python\python310\lib\genericpath.py
Type:      function
参数说明: 
1.path: 表示要判断的路径,可以采用绝对路径,也可以采用相对路径。
2.返回值: 如果给定的路径对应的文件是普通文件,则返回True,否则返回False

示例:

In [66]: # 1.根据绝对路径判断文件是否为普通文件

In [67]: os.path.isfile(r'C:\Users\amoxiang\test.py')
Out[67]: True

In [68]: os.path.isfile(r'C:\Users\amoxiang\data.csv')
Out[68]: True

In [69]: os.path.isfile(r'C:\Users\amoxiang\data.py')  # 如果指定的文件不存在,则返回False
Out[69]: False

2.10 isdir()方法——判断是否为目录

isdir() 方法用于判断指定的路径是否为目录。语法格式如下:

In [70]: os.path.isdir?
Signature: os.path.isdir(s)
Docstring: Return true if the pathname refers to an existing directory.
File:      f:\dev_tools\python\python310\lib\genericpath.py
Type:      function

参数说明: 
1.path: 表示要判断的路径,可以采用绝对路径,也可以采用相对路径。
2.返回值: 如果给定的路径是目录,则返回True,否则返回False

示例:

In [71]: os.path.isdir(r'C:\Users\amoxiang\data.csv')
Out[71]: False

In [72]: os.path.isdir(r'C:\Users\amoxiang')
Out[72]: True

# ps: 如果指定的目录不存在,则返回False
In [73]: os.path.isdir(r'C:\Users\amoxiang\test')
Out[73]: False

2.11 islink()方法——判断指定目录是否为符号链接

islink() 方法用于判断指定的目录是否为符号链接(也称为软链接)。如果使用的 Python 运行时不支持符号链接,则总是返回 False。语法格式如下:

In [74]: os.path.islink?
Signature: os.path.islink(path)
Docstring:
Test whether a path is a symbolic link.
This will always return false for Windows prior to 6.0.
File:      f:\dev_tools\python\python310\lib\ntpath.py
Type:      function

参数说明: 
1.path: 表示要判断的路径。
2.返回值: 如果给定的路径为符号链接,并且Python运行时支持符号链接,则返回True,否则返回False

示例:

# linux下
[root@VM-16-6-centos ~]# python3
Python 3.8.10 (default, Jun 28 2024, 03:45:43) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os.path
>>> os.path.islink('/lib64')
True

# windows下
In [75]: os.path.islink(r'C:\Users\amoxiang\test')
Out[75]: False

2.12 commonpath()方法——提取共有的最长路径

commonpath() 方法用于从一个目录列表中提取各个路径共有的最长路径。如果目录列表为空,或者各路径间没有共有路径,则返回空字符串。语法格式如下:

In [76]: os.path.commonpath?
Signature: os.path.commonpath(paths)
Docstring: Given a sequence of path names, returns the longest common sub-path.
File:      f:\dev_tools\python\python310\lib\ntpath.py
Type:      function

参数说明: 
1.paths: 表示要提取路径的目录列表。
2.返回值: 返回提取后的字符串。

示例:

import os.path  # 导入os.path模块

pathlist = [r'D:\Code\dream\PythonStudy\base\day04-函数',
            r'D:\Code\dream\PythonStudy\base\day8-并发编程',
            r'D:\Code\dream\PythonStudy\base\day06-文件IO和序列化\csv_demo.py']  # 目录列表

# D:\Code\dream\PythonStudy\base
print(os.path.commonpath(pathlist))  # 打印最长的共有路径

2.13 commonpref ix()方法——提取共有的路径前缀

commonprefix() 方法用于从一个目录列表中提取各个路径共有的前缀。如果目录列表为空,或者各路径间没有共有前缀,则返回空字符串。语法格式如下:

In [77]: os.path.commonprefix?
Signature: os.path.commonprefix(m)
Docstring: Given a list of pathnames, returns the longest common leading component
File:      f:\dev_tools\python\python310\lib\genericpath.py
Type:      function
参数说明: 
1.m: 表示要提取前缀的目录列表。
2.返回值: 返回提取后的字符串。
说明: 由于该方法一次只能处理一个字符,所以可能会返回无效路径。要获得有效路径,请使用commonpath()方法。

示例:

# 从多个路径中提取共有的前缀
import os.path  # 导入os.path模块

pathlist = [r'E:/demo/temp.txt', r'E:/demo/test/test.txt', r'E:/demo/test.txt']  # 目录列表
print(os.path.commonprefix(pathlist))  # 打印最长的共有路径前缀

2.14 getatime()方法——获取最后一次访问路径的时间

getatime() 方法用于获取最后一次访问路径的时间。语法格式如下:

In [78]: os.path.getatime?
Signature: os.path.getatime(filename)
Docstring: Return the last access time of a file, reported by os.stat().
File:      f:\dev_tools\python\python310\lib\genericpath.py
Type:      function

参数说明: 
1.path: 表示要获取的最后一次访问时间的路径,可以采用绝对路径,也可以采用相对路径。
2.返回值: 返回从纪元开始到最后一次访问该路径的秒数,值为浮点数。

示例:

import time  # 导入时间模块
import os.path  # 导入os.path模块

mtime = os.path.getatime(r'C:\Users\amoxiang\data.csv')  # 获取路径最后一次访问时间
# 1726528262.4639144
# 2024-09-17 07:11:02
print(mtime)  # 打印秒数
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(mtime)))  # 转换为日期时间

2.15 getmtime()方法——获取最后一次修改路径的时间

getmtime() 方法用于获取最后一次修改路径的时间。语法格式如下:

In [79]: os.path.getmtime?
Signature: os.path.getmtime(filename)
Docstring: Return the last modification time of a file, reported by os.stat().
File:      f:\dev_tools\python\python310\lib\genericpath.py
Type:      function
参数说明: 
1.path: 表示要获取的最后一次修改时间的路径,可以采用绝对路径,也可以采用相对路径。
2.返回值: 返回从纪元开始到最后一次修改该路径的秒数,值为浮点数。

示例:

import time  # 导入时间模块
import os.path  # 导入os.path模块

mtime = os.path.getmtime(r'C:\Users\amoxiang\data.csv')  # 获取路径最后一次修改时间
# 1726528417.0766008
# 2024-09-17 07:13:37
print(mtime)  # 打印秒数
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(mtime)))  # 转换为日期时间

2.16 getctime()方法——获取路径的ctime

getctime() 方法用于获取路径的 ctime。这里的 ctime 由于操作系统的不同,代表的意思也不同。例如,在 Unix 系统中它的含义为最后一次元数据更改的时间;在 Windows 系统中它的含义则是创建时间。语法格式如下:

In [80]: os.path.getctime?
Signature: os.path.getctime(filename)
Docstring: Return the metadata change time of a file, reported by os.stat().
File:      f:\dev_tools\python\python310\lib\genericpath.py
Type:      function
参数说明: 
1.path: 表示获取的最后一次修改时间或创建时间的路径,可以采用绝对路径,也可以采用相对路径。
2.返回值: 返回从纪元开始到创建或最后一次更改该路径的秒数,值为浮点数。

示例:

import time  # 导入时间模块
import os.path  # 导入os.path模块

# 如果文件或者是文件夹不存在,会抛出异常
mtime = os.path.getctime(r'C:\Users\amoxiang\data.csv')  # 获取路径的创建时间
# 1726254694.2870502
# 2024-09-14 03:11:34
print(mtime)  # 打印秒数
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(mtime)))  # 转换为日期时间

2.17 getsize()方法——获取路径的大小

getsize() 方法用于获取路径(目录或者文件)的大小(以字节为单位)。如果路径不存在或者无法访问,则抛出 OSError 异常。语法格式如下:

In [81]: os.path.getsize?
Signature: os.path.getsize(filename)
Docstring: Return the size of a file, reported by os.stat().
File:      f:\dev_tools\python\python310\lib\genericpath.py
Type:      function
参数说明: 
1.filename: 表示要获取大小的路径,可以采用绝对路径,也可以采用相对路径。
2.返回值: 返回路径的大小,以字节为单位。如果指定的 filename 为文件,则返回该文件的大小。如果 filename 为目录,
则返回描述该目录信息的文件的大小
例如,在Windows10系统中,获取某个目录的大小可能得到4096),并不是目录下全部文件的大小。

示例:

import os.path  # 导入os.path模块

# 如果文件或者是文件夹不存在,会抛出异常
print(os.path.getsize(r'C:\Users\amoxiang\data.csv'))  # 打印文件的大小 16


# 获取指定文件的大小并格式化字节数
def format_byte(num):
    """
    格式化文件大小的函数
    :param num: 要格式化的字节数
    :return:
    """
    for (scale, label) in [(1024 * 1024 * 1024, 'GB'), (1024 * 1024, 'MB'), (1024, 'KB')]:
        if num >= scale:  # 如果文件大小大于等于1KB
            return '%.2f %s' % (num * 1.0 / scale, label)
        elif num == 1:  # 如果文件大小为1字节
            return '1字节'
        else:  # 处理小于1KB的情况
            byte = '%.2f' % (num or 0)
    # 去掉结尾的.00,并且加上单位"字节"
    return (byte[:-3] if byte.endswith('.00') else byte) + '字节'


filesize = os.path.getsize(r'D:\video\03.JavaScript基础\01.为什么要学JavaScript.mp4')  # 获取文件的大小
print(format_byte(filesize))

2.18 isabs()方法——判断是否为绝对路径

isabs() 方法用于判断路径是否为绝对路径。语法格式如下:

In [82]: os.path.isabs?
Signature: os.path.isabs(s)
Docstring: Test whether a path is absolute
File:      f:\dev_tools\python\python310\lib\ntpath.py
Type:      function

参数说明: 
1.path: 表示要判断的路径,可以采用绝对路径,也可以采用相对路径。
2.返回值: 如果给定的路径是绝对路径,则返回True,否则返回False。
说明: 在Unix系统中,将以斜杠开头的路径视为绝对路径;而在Windows系统中,以去除驱动器号后的(反向)斜线开头的视为绝对路径。

示例:

# linux下
[root@VM-16-6-centos ~]# python3
Python 3.8.10 (default, Jun 28 2024, 03:45:43) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os.path
>>> os.path.isabs('/root')
True
>>> os.path.isabs('/xxx')
True
>>> os.path.isabs('/AntiSpider/templates')
True
>>> os.path.isabs('AntiSpider/templates')
False

# windows下
In [83]: os.path.isabs('c:/user/amoxiang/')
Out[83]: True

In [84]: os.path.isabs('user/amoxiang/')
Out[84]: False

In [85]: os.path.isabs('/user/amoxiang/')
Out[85]: True

2.19 ismount()方法——判断是否为挂载点

ismount() 方法用于判断一个路径是否为挂载点。语法格式如下:

In [86]: os.path.ismount?
Signature: os.path.ismount(path)
Docstring:
Test whether a path is a mount point (a drive root, the root of a
share, or a mounted volume)
File:      f:\dev_tools\python\python310\lib\ntpath.py
Type:      function

参数说明: 
1.path: 表示要判断的路径。
2.返回值: 如果给定的路径是挂载点,则返回True,否则返回False。在Windows系统中,驱动器盘符根目录和共享UNC始终是挂载点。

示例:

In [87]: os.path.ismount('d:/')
Out[87]: True

In [88]: os.path.ismount('d:/code')
Out[88]: False

2.20 normcase()方法——规范化路径名称的大小写

normcase() 方法用于规范化路径名称的大小写。语法格式如下:

In [89]: os.path.normcase?
Signature: os.path.normcase(s)
Docstring:
Normalize case of pathname.

Makes all characters lowercase and all slashes into backslashes.
File:      f:\dev_tools\python\python310\lib\ntpath.py
Type:      function

参数说明: 
1.s: 表示要规范的路径,可以采用绝对路径,也可以采用相对路径。
2.返回值: 返回规范后的路径。在Windows系统中,将路径名称中的所有字符转换为小写形式,
并将正斜杠"/"转换为反斜杠"\";在不区分大小写的操作系统中,返回原路径。

示例:

In [90]: path1 = 'd:/Code/dream'

In [91]: path1
Out[91]: 'd:/Code/dream'

In [94]: os.path.normcase(path1)
Out[94]: 'd:\\code\\dream'

2.21 normpath()方法——规范路径名称

normpath() 方法用于规范路径名称。该方法的实现主要通过折叠冗余分隔符和上一级引用两种方式来规范路径名,例如,将 A//BA/B/A/./BA/foo/../B 都转换为 A/B。该操作可能会更改包含符号链接的路径的本来含义。在 Windows 系统中,它将正斜杠转换为反斜杠。语法格式如下:

In [95]: os.path.normpath?
Signature: os.path.normpath(path)
Docstring: Normalize path, eliminating double slashes, etc.
File:      f:\dev_tools\python\python310\lib\ntpath.py
Type:      function
参数说明: 
1.path: 表示要规范的路径,可以采用绝对路径,也可以采用相对路径。
2.返回值: 返回规范后的路径。

示例:

In [96]: path1
Out[96]: 'd:/Code/dream'

In [97]: path1 = r'd:/Code/dream\PythonStudy\base'

In [98]: path1
Out[98]: 'd:/Code/dream\\PythonStudy\\base'

In [100]: os.path.normpath(path1)
Out[100]: 'd:\\Code\\dream\\PythonStudy\\base'

2.22 samef ile()方法——比较两个路径是否相同

samefile() 方法用于比较两个路径是否为同一个文件或目录。语法格式如下:

In [100]: os.path.normpath(path1)
Out[100]: 'd:\\Code\\dream\\PythonStudy\\base'

In [101]: os.path.samefile?
Signature: os.path.samefile(f1, f2)
Docstring:
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.
File:      f:\dev_tools\python\python310\lib\genericpath.py
Type:      function

参数说明: 
1.path1: 表示路径1,可以采用绝对路径,也可以采用相对路径。
2.path2: 表示路径2,可以采用绝对路径,也可以采用相对路径。
3.返回值: 如果路径1和路径2为同一个文件或目录,则返回True,否则返回False

示例:

In [109]: f1 = 'c:/users/amoxiang/test_data'

In [110]: f2 = './test_data'

In [111]: os.path.samefile(f1, f2)
Out[111]: True

In [112]: f1 = 'c:/'

In [113]: f2 = '../../../'

In [114]: os.path.samefile(f1, f2)
Out[114]: True

In [115]: f1 = 'c:/'

In [116]: f2 = './test_data'

In [117]: os.path.samefile(f1, f2)
Out[117]: False

2.23 sameopenf ile()方法——比较两个打开的 文件描述符对象是否为同一个文件

sameopenfile() 方法用于比较两个打开的文件描述符对象是否为同一个文件。语法格式如下:

In [118]: os.path.sameopenfile?
Signature: os.path.sameopenfile(fp1, fp2)
Docstring: Test whether two open file objects reference the same file
File:      f:\dev_tools\python\python310\lib\genericpath.py
Type:      function
参数说明: 
1.fp1: 表示打开的文件描述符对象,可以通过os.open()方法或者open().fileno()方法创建。
2.fp2: 表示打开的文件描述符对象,可以通过os.open()方法或者open().fileno()方法创建。
3.返回值: 如果两个文件描述符对象为同一个文件,则返回True,否则返回False

示例:

# 判断两个打开的文件描述符对象是否为同一个文件
import os.path  # 导入os.path模块

fp1 = open(r'csv_demo.py', 'r').fileno()  # 第一个文件描述符对象
fp2 = os.open(r'csv_demo.py', os.O_RDONLY)  # 第二个文件描述符对象
print(os.path.sameopenfile(fp1, fp2))  # 判断两个文件对象是否为同一个文件 True

2.24 samestat()方法——判断两个stat元组是否指向同一个文件

samestat() 方法用于判断两个文件信息元组是否指向同一个文件。语法格式如下:

In [119]: os.path.samestat?
Signature: os.path.samestat(s1, s2)
Docstring: Test whether two stat buffers reference the same file
File:      f:\dev_tools\python\python310\lib\genericpath.py
Type:      function

参数说明: 
1.stat1: 表示文件信息元组,可以通过os.stat()方法获取。
2.stat2: 表示文件信息元组,可以通过os.stat()方法获取。
3.返回值: 如果给定的路径存在,则返回True,否则返回False

示例:

import os.path  # 导入os.path模块

path = r'csv_demo.py'  # 文件路径
stat1 = os.stat(path)  # 第一个stat元组
stat2 = os.stat(os.open(path, os.O_RDONLY))  # 第二个stat元组
print(os.path.samestat(stat1, stat2))  # 判断两个stat元组是否为同一个文件 True
stat3 = os.stat(os.open(r'csv_reader_demo.py', os.O_RDONLY))  # 第三个stat元组
print(os.path.samestat(stat1, stat3))  # 判断两个stat元组是否为同一个文件 False

2.25 realpath()方法——获取实际路径

realpath() 方法用于返回指定路径的实际路径。当操作系统支持符号链接时,还会去掉路径中遇到的任何符号链接。语法格式如下:

In [120]: os.path.realpath?
Signature: os.path.realpath(path, *, strict=False)
Docstring: <no docstring>
File:      f:\dev_tools\python\python310\lib\ntpath.py
Type:      function

参数说明: 
1.path: 表示具体的路径,可以采用绝对路径,也可以采用相对路径。
2.返回值: 如果给定的路径存在,则返回True,否则返回False。
ps: realpath()方法在获取实际路径时,并不会检查路径是否真实存在,只是把当前文件目录与realpath()方法给定的路径进行拼接。

示例:

import os.path  # 导入os.path模块

# D:\Code\dream\PythonStudy\base\day06-文件IO和序列化\csv_demo.py
print(os.path.realpath(r'csv_demo.py'))  # 获取文件的实际路径
print(os.path.realpath(os.path.basename(__file__)))

os.path 模块的 abspath() 方法与 realpath() 方法的区别是,在支持符号链接的系统中,abspath() 方法不处理符号链接,而 realpath() 方法则先处理路径中的符号链接,再返回绝对路径。

[root@VM-16-6-centos ~]# python3
Python 3.8.10 (default, Jun 28 2024, 03:45:43) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os.path
>>> print(os.path.realpath(r'/lib'))
/usr/lib
>>> print(os.path.abspath(r'/lib'))
/lib

2.26 relpath()方法——计算相对路径

relpath() 方法用于返回从当前工作目录到指定目录的相对路径。语法格式如下:

In [121]: os.path.relpath?
Signature: os.path.relpath(path, start=None)
Docstring: Return a relative version of a path
File:      f:\dev_tools\python\python310\lib\ntpath.py
Type:      function

参数说明: 
1.path: 表示要计算的路径,可以采用绝对路径,也可以采用相对路径。当采用绝对路径时,需要与当前工作目录在同一磁盘驱动器上。
2.start: 可选参数,默认值为os.curdir(当前工作目录)。参数值可以直接使用字符串指定从哪里开始计算相对路径。
3.返回值: 返回从当前工作目录到指定目录的相对路径。
ps: 说明:使用relpath()方法计算相对路径时,并不访问文件系统以确定路径是否真实存在。

示例:

import os.path  # 导入os.path模块

# D:\Code\dream\PythonStudy\base\day06-文件IO和序列化\os_path_demo.py
print(os.path.relpath(r'D:\Code\dream\PythonStudy\base'))  # 计算相对路径 ..
print(os.path.relpath(r'D:\Code\dream\PythonStudy\base\day06-文件IO和序列化', 'dream'))  # 计算相对路径 ..
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Amo Xiang

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

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

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

打赏作者

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

抵扣说明:

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

余额充值