您现在的位置是:首页 > 技术教程 正文

Python 程序设计入门(025)—— 使用 os 模块操作文件与目录

admin 阅读: 2024-03-22
后台-插件-广告管理-内容页头部广告(手机)

Python 程序设计入门(025)—— 使用 os 模块操作文件与目录

目录

  • Python 程序设计入门(025)—— 使用 os 模块操作文件与目录
    • 一、操作目录的常用函数
        • 1、os 模块提供的操作目录的函数
        • 2、os.path 模块提供的操作目录的函数
    • 二、相对路径与绝对路径
        • 1、相对路径
        • 2、绝对路径
    • 三、目录操作
        • 1、获取当前工作目录:getcwd() 函数
        • 2、设置当前工作目录:chdir() 函数
        • 3、查看指定路径下的文件和目录信息:listdir() 函数
        • 4、获取文件的绝对路径:abspath() 函数
        • 5、拼接路径:join() 函数
        • 6、判断目录或文件是否存在:exists() 函数
        • 7、创建目录:mkdir() 函数与 makedirs() 函数
        • (1)创建一级目录:mkdir() 函数
        • (2)创建多级目录:makedirs() 函数
        • 8、删除目录:rmdir() 函数与 removedirs() 函数
        • (1)删除一级空目录:rmdir() 函数
        • (2)删除多级目录:removedirs() 函数
        • 9、遍历目录:walk() 函数
    • 四、文件操作
        • 1、获取文件基本信息:stat() 函数
        • 2、删除文件:remove() 函数
        • 3、重命名文件与目录:rename() 函数
        • 4、分离文件名和扩展名:splitext() 函数
        • 5、从一个目录中提取文件名:basename() 函数
        • 6、从一个目录中提取文件路径,不包含文件名:dirname() 函数
        • 7、判断一个目录是否为路径:isdir() 函数

Python 内置了 os 模块及其子模块 os.path,用于对目录或文件进行操作。在使用 os 模块及其子模块 os.path 模块时,需要使用 import 导入该模块,才能使用它们提供的函数或方法。

一、操作目录的常用函数

1、os 模块提供的操作目录的函数

os 模块提供的操作目录的函数如下表所示:

函数说明
getcwd()返回当前的工作目录
listdir(path)返回指定路径下的文件和目录信息
mkdir(path[,mode])创建目录
makedirs(path1/path2…[,mode])创建多级目录
rmdir(path)删除目录
removedirs(path1/path2…)删除多级目录
chdir(path)将 path 设置为当前工作目录
walk(top [,topdown [,onerror]])遍历目录树。该函数返回一个元组,包括所有路径名、目录列表和
文件列表3个元素
2、os.path 模块提供的操作目录的函数

os.path 模块提供的操作目录的函数如下表所示:

函数说明
abspath(path)获取文件目录的绝对路径
exists(path)判断目录或者文件是否存在,如果存在返回True,否则返回False
join(path, name)将目录与目录或文件名拼接起来
splitext()分离文件名和扩展名
basename(path)从一个目录中提取文件名
dirname(path)从一个路径中提取文件路径,不包括文件名
isdir(path)判断是否为路径

二、相对路径与绝对路径

1、相对路径

当前工作目录指当前文件所在的目录。可以通过 os 模块的 getcwd() 函数获取当前工作目录。

代码如下:

import os print("当前工作目录:",os.getcwd()) 程序运行结果如下: ===================== RESTART: C:\Python\Python38\First.py ===================== 当前工作目录: C:\Python\Python38
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

相对路径是依赖于当前工作目录的。如果在当前工作目录下有一个文件 stu.txt,在打开该文件时,可以直接使用文件名,此时使用的就是相对路径。文件 stu.txt 的实际路径就是当前工作目录【C:\Python\Python38】再加上相对路径,即:【C:\Python\Python38/stu.txt】。如果当前目录下有子目录 test,并且子目录中有一个文件 test.txt,那么在打开该文件时应用使用【test/test.txt】。

代码如下:

(1)使用相对路径打开 stu.txt

import os print("当前工作目录:",os.getcwd()) with open("stu.txt","r",encoding="utf-8") as file1: # 使用相对路径 print(file1.readline()) 程序运行结果如下: ===================== RESTART: C:\Python\Python38\First.py ===================== 当前工作目录: C:\Python\Python38 姓名,性别,出生日期,院系,班级,手机号
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

(2)使用相对路径打开 test.txt

import os print("当前工作目录:",os.getcwd()) with open("test/test.txt","r",encoding="utf-8") as file1: # 使用相对路径 print(file1.readline()) 程序运行结果如下: ===================== RESTART: C:\Python\Python38\First.py ===================== 当前工作目录: C:\Python\Python38 测试文件,内容如下:
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

(3)使用绝对路径打开以上两个文件

import os print("当前工作目录:",os.getcwd()) print("文件stu.txt的内容如下:") with open("C:/Python/Python38/stu.txt","r",encoding="utf-8") as file1: print(file1.readline()) print("文件test.txt的内容如下:") with open("C:/Python/Python38/test/test.txt","r",encoding="utf-8") as file1: print(file1.readline()) 程序运行结果如下: ===================== RESTART: C:\Python\Python38\First.py ===================== 当前工作目录: C:\Python\Python38 文件stu.txt的内容如下: 姓名,性别,出生日期,院系,班级,手机号 文件test.txt的内容如下: 测试文件,内容如下:
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
2、绝对路径

绝对路径是指在使用文件时指定文件的实际路径,绝对路径不依赖于当前工作目录。可以通过 os.path 模块的 abspath() 函数获取一个文件的绝对路径。

例如:

import os print("当前工作目录:",os.getcwd()) print("文件stu.txt的绝对路径为:") print(os.path.abspath("stu.txt")) print("文件test.txt的绝对路径为:") print(os.path.abspath("test/test.txt")) 程序运行结果如下: ===================== RESTART: C:\Python\Python38\First.py ===================== 当前工作目录: C:\Python\Python38 文件stu.txt的绝对路径为: C:\Python\Python38\stu.txt 文件test.txt的绝对路径为: C:\Python\Python38\test\test.txt
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

三、目录操作

1、获取当前工作目录:getcwd() 函数

使用 os 模块的 getcwd() 函数可以获取当前工作目录。getcwd() 函数的语法格式如下:

os.getcwd()
  • 1

例如:

import os print("当前工作目录:",os.getcwd()) 程序运行结果如下: ===================== RESTART: C:\Python\Python38\First.py ===================== 当前工作目录: C:\Python\Python38
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
2、设置当前工作目录:chdir() 函数

使用 os 模块的 chdir() 函数可以把某个目录设置为当前工作目录。chdir() 函数的语法格式如下:

os.chdir(path)
  • 1

例如:

import os print("当前工作目录:",os.getcwd()) # 查看当前工作目录 os.chdir("D:\\erp\\") # 设置当前工作目录 print("当前工作目录:",os.getcwd()) # 查看当前工作目录 os.chdir("C:\\Python\\Python38") # 重新设置当前工作目录 print("当前工作目录:",os.getcwd()) # 查看当前工作目录 程序运行结果如下: ===================== RESTART: C:\Python\Python38\First.py ===================== 当前工作目录: C:\Python\Python38 当前工作目录: D:\erp 当前工作目录: C:\Python\Python38
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
3、查看指定路径下的文件和目录信息:listdir() 函数

使用 os.path 模块的 listdir() 函数可以查看某个路径下的文件和目录信息。listdir() 函数的语法格式如下:

os.listdir(path) 说明:返回类型为列表。
  • 1
  • 2
  • 3

例如:

import os list1 = os.listdir("C:\\Python\\Python38\\") print(type(list1)) print(list1) 程序运行结果如下: ===================== RESTART: C:\Python\Python38\First.py ===================== <class 'list'> ['aa.txt', 'Date0819', 'DLLs', 'Doc', 'First.py', 'include', 'Lib', 'libs', 'LICENSE.txt', 'MyData', 'MyTest', 'NEWS.txt', 'python.exe', 'python3.dll', 'python38.dll', 'pythonw.exe', 'Scripts', 'stu.txt', 'tcl', 'test', 'Tools', 'vcruntime140.dll', 'vcruntime140_1.dll']
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
4、获取文件的绝对路径:abspath() 函数

使用 os.path 模块的 abspath() 函数可以获取一个文件的绝对路径。abspath() 函数的语法格式如下:

os.path.abspath(path) 说明:path 为要获取绝对路径的相对路径,可以是文件或目录。
  • 1
  • 2

例如:

import os print("当前工作目录:",os.getcwd()) print("文件stu.txt的绝对路径为:") print(os.path.abspath("stu.txt")) print("文件test.txt的绝对路径为:") print(os.path.abspath("test/test.txt")) 程序运行结果如下: ===================== RESTART: C:\Python\Python38\First.py ===================== 当前工作目录: C:\Python\Python38 文件stu.txt的绝对路径为: C:\Python\Python38\stu.txt 文件test.txt的绝对路径为: C:\Python\Python38\test\test.txt
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
5、拼接路径:join() 函数

如果要将两个或者多个路径拼接组成一个新的路径,可以使用 os.path 模块的 join() 函数来实现。join() 函数的语法格式如下:

os.path.join(path1 [, path2 [, ...]]) 说明: (1)path1、path2、... 表示要拼接的文件路径。 (2)如果要路径的路径都是相对路径,则拼接出来的结果将是一个相对路径。 (3)如果要拼接的路径中存在多个绝对路径,则以从左到右最后一次出现的路径为准,并且该路径之前的参数都被忽略。
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

例如:

import os print(os.path.join("C:\\Python\\Python38","stu.txt")) # 路径与文件拼接 print(os.path.join("C:\\Python\\Python38","test\\test.txt")) # 路径与路径拼接 print(os.path.join("test","test.txt")) # 两个相对路径拼接 print(os.path.join("d:\\","C:\\Python\\Python38\\")) # 两个绝对路径拼接 程序运行结果如下: ===================== RESTART: C:\Python\Python38\First.py ===================== C:\Python\Python38\stu.txt C:\Python\Python38\test\test.txt test\test.txt C:\Python\Python38\
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
6、判断目录或文件是否存在:exists() 函数

使用 os.path 模块的 exists() 函数判断给定的目录或文件是否存在。exists() 函数的语法格式如下:

os.path.exists(path) 说明: (1)path:要判断的目录,可以采用绝对路径,也可以采用相对路径。 (2)如果给定的路径存在,返回 True,否则返回 False
  • 1
  • 2
  • 3
  • 4

例如:

import os print(os.path.exists("C:\\Python\\Python38\\")) # 绝对路径 print(os.path.exists("stu.txt")) #相对路径 print(os.path.exists("test\\test.txt")) #相对路径 程序运行结果如下: ===================== RESTART: C:\Python\Python38\First.py ===================== True True True
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
7、创建目录:mkdir() 函数与 makedirs() 函数

os 模块提供了两个创建目录的函数:mkdir() 函数与 makedirs() 函数。其中 mkdir() 函数用于创建一级目录,makedirs() 函数用于创建多级目录。

(1)创建一级目录:mkdir() 函数

创建一级目录是指一次只能创建一级目录。使用 mkdir() 函数只能创建指定路径中的最后一级目录,如果该目录的上一级目录不存在,则抛出异常:FileNotfoundError 。mkdir() 函数的语法格式如下:

os.mkdir(path,mode = 0777) 说明: (1)path:指定要创建的目录,可以使用绝对路径,也可以使用相对路径。 (2)mode:指定数值模式(文件权限),默认值为 0777。在非 unix 系统上无效或被忽略。
  • 1
  • 2
  • 3
  • 4

例如:

使用相对路径,在当前工作目录中创建目录。

代码如下:

import os os.mkdir("MyData") # 在当前工作目录中创建目录 MyData print(os.path.exists("C:\\Python\\Python38\\MyData")) 程序运行结果如下: ===================== RESTART: C:\Python\Python38\First.py ===================== True
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

使用绝对路径,在当前工作目录中创建目录。

代码如下:

import os os.mkdir("C:\\Python\\Python38\\MyTest") print(os.path.exists("C:\\Python\\Python38\\MyData")) 程序运行结果如下: ===================== RESTART: C:\Python\Python38\First.py ===================== True
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

上级目录不存在:

import os os.mkdir("C:\\Python\\Python380\\MyTest") print(os.path.exists("C:\\Python\\Python38\\MyData")) 程序运行结果如下: ===================== RESTART: C:\Python\Python38\First.py ===================== Traceback (most recent call last): File "C:\Python\Python38\First.py", line 2, in <module> os.mkdir("C:\\Python\\Python380\\MyTest") FileNotFoundError: [WinError 3] 系统找不到指定的路径。: 'C:\\Python\\Python380\\MyTest'
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
(2)创建多级目录:makedirs() 函数

创建多级目录使用 os 模块提供的 makedirs() 函数,该函数使用递归的方式创建目录。makedirs() 函数的语法格式如下:

os.makedirs(name, mode = 0777) 说明: (1)name:要创建的目录,可以使用绝对路径,也可以使用相对路径。 (2)mode:指定数值模式(文件权限),默认值为 0777。该参数在非 unix 系统上无效或忽略。
  • 1
  • 2
  • 3
  • 4

例如:

import os os.makedirs("F:\\Python\\MyTest\\Date001\\program\\") # 使用绝对路径创建目录 os.makedirs("Date0819\\doc\\") # 使用相对路径,在当前工作目录下创建子目录 print(os.path.exists("F:\\Python\\MyTest\\Date001\\program\\")) print(os.path.exists("C:\\Python\\Python38\\Date0819\\doc\\")) 程序运行结果如下: ===================== RESTART: C:\Python\Python38\First.py ===================== True True
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

如果在创建目录时,目录已经存在,则抛出异常:FileExistsError。可以在创建目录前,先判断要创建的目录是否存在,只有当目录不存在时才创建目录。

目录已存在,抛出异常:

import os os.makedirs("F:\\Python\\MyTest\\Date001\\program\\") 程序运行结果如下: ===================== RESTART: C:\Python\Python38\First.py ===================== Traceback (most recent call last): File "C:\Python\Python38\First.py", line 2, in <module> os.makedirs("F:\\Python\\MyTest\\Date001\\program\\") File "C:\Python\Python38\lib\os.py", line 223, in makedirs mkdir(name, mode) FileExistsError: [WinError 183] 当文件已存在时,无法创建该文件。: 'F:\\Python\\MyTest\\Date001\\program\\'
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

先判断目录是否存在,如果不存在再创建目录:

import os if os.path.exists("F:\\Python\\MyTest\\Date001\\program\\"): print("要创建的目录已存在,不能创建同名的目录!") else: os.makedirs("F:\\Python\\MyTest\\Date001\\program\\") print("目录创建成功!") 程序运行结果如下: ===================== RESTART: C:\Python\Python38\First.py ===================== 要创建的目录已存在,不能创建同名的目录!
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
8、删除目录:rmdir() 函数与 removedirs() 函数

使用 rmdir() 函数与 removedirs() 函数可以删除目录,但必须是空目录才能被删除。否则会抛出异常:OSError: [WinError 145] 目录不是空的。

(1)删除一级空目录:rmdir() 函数

使用 rmdir() 函数可以删除最底层的空目录。rmdir() 函数的语法格式如下:

os.rmdir(path)
  • 1

例如:

目录非空,删除失败:

import os os.rmdir("F:\\Python\\") 程序运行结果如下: ===================== RESTART: C:\Python\Python38\First.py ===================== Traceback (most recent call last): File "C:\Python\Python38\First.py", line 2, in <module> os.rmdir("F:\\Python\\") OSError: [WinError 145] 目录不是空的。: 'F:\\Python\\'
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

删除最后一级目录,删除成功:

import os print(os.path.exists("F:\\Python\\MyTest\\Date001\\program")) os.rmdir("F:\\Python\\MyTest\\Date001\\program") # 删除最后一级目录 print(os.path.exists("F:\\Python\\MyTest\\Date001\\program"))#目录不存在 print(os.path.exists("F:\\Python\\MyTest\\Date001\\"))#目录存在 程序运行结果如下: ===================== RESTART: C:\Python\Python38\First.py ===================== True False True
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
(2)删除多级目录:removedirs() 函数

使用 removedirs() 函数可以删除多级目录。removedirs() 函数的语法格式如下:

os.removedirs(path)
  • 1

例如:

import os print(os.path.exists("F:\\Python\\MyTest\\Date001\\program")) os.removedirs("F:\\Python\\MyTest\\Date001\\program") # 删除目录 F:\Python\MyTest\Date001\program、F:\Python\MyTest\Date001、 # F:\Python\MyTest 以及 F:\Python print(os.path.exists("F:\\Python\\MyTest\\Date001\\program"))#目录不存在 print(os.path.exists("F:\\Python\\MyTest\\Date001")) #目录不存在 print(os.path.exists("F:\\Python")) #目录不存在 print(os.path.exists("F:")) #目录不存在 程序运行结果如下: ===================== RESTART: C:\Python\Python38\First.py ===================== True False False False True
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
9、遍历目录:walk() 函数

使用 walk() 函数可以将指定目录下的全部目录(包括子目录)和文件浏览一遍。walk() 函数的语法格式如下:

os.walk(top [,topdown] [,onerror] [,followlinks]) 说明: (1)top:指定要遍历的根目录。 (2)topdown:指定遍历的顺序,如果值为 True,则表示自上而下遍历(先遍历根目录),如果为 False,则表示自下而上遍历(先遍历最后一级子目录),默认值为 True。 (3)onerror:指定错误的处理方式(默认为忽略)。 (4)followlinks:将该参数设置为 True,指定在支持的系统上访问由符号链接指向的目录。默认情况下(False),walk() 函数不会向下转换成解析到目录的符号链接。 (5)返回值:包括3个元素的元组生成器对象(dirpath,dirname,filenames),其中:dirpath 表示当前遍历的目录,是一个字符串;dirname 表示当前目录下包含的子目录,是一个列表;filenames 表示当前目录下包含的文件,是一个列表。
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

例如:

遍历当前目录下的文件和目录:

import os os.chdir("D:\\erp") for dirpath,dirname,filenames in os.walk("."): print("="*30) print(dirpath) print(dirname) print(filenames) 程序运行结果如下: ===================== RESTART: C:\Python\Python38\First.py ===================== ============================== D:\erp 目录下有4个目录,1个文件 . ['2021-12-2', '2022-1-2', '2023-5-6', '2023-8-17'] ['etd-0712106-140843.pdf'] ==============================D:\erp\2021-12-2 目录下有2个目录,0个文件 .\2021-12-2 ['1', '2'] [] ==============================D:\erp\2021-12-2\1 目录下有0个目录,1个文件 .\2021-12-2\1 [] ['093TKU00385003-001.pdf'] ==============================D:\erp\2021-12-2\2 目录下有0个目录,1个文件 .\2021-12-2\2 [] ['094CJU00457081-001.pdf'] ==============================D:\erp\2022-1-2 目录下有0个目录,3个文件 .\2022-1-2 [] ['381001.pdf', '90421037.pdf', '90423009.pdf'] ==============================D:\erp\2023-5-6 目录下有0个目录,2个文件 .\2023-5-6 [] ['etd-0704106-174528.pdf', 'etd-0710106-133405.pdf'] ==============================D:\erp\2023-8-17 目录下有0个目录,1个文件 .\2023-8-17 [] ['qqq.pdf']
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38

遍历指定目录下的文件和目录:

import os for dirpath,dirname,filenames in os.walk("C:\\Python\\Python38\\Tools\\pynche"): print("="*30) print(dirpath) print(dirname) print(filenames) 程序运行结果如下: ===================== RESTART: C:\Python\Python38\First.py ===================== ==============================目录 C:\\Python\\Python38\\Tools\\pynche下有 2 个目录,17 个文件 C:\Python\Python38\Tools\pynche ['X', '__pycache__'] ['ChipViewer.py', 'ColorDB.py', 'DetailsViewer.py', 'html40colors.txt', 'ListViewer.py', 'Main.py', 'namedcolors.txt', 'pyColorChooser.py', 'pynche.pyw', 'PyncheWidget.py', 'StripViewer.py', 'Switchboard.py', 'TextViewer.py', 'TypeinViewer.py', 'webcolors.txt', 'websafe.txt', '__init__.py'] ==============================目录 C:\Python\Python38\Tools\pynche\X下有 0 个目录,1 个文件 C:\Python\Python38\Tools\pynche\X [] ['rgb.txt', 'xlicense.txt'] ==============================目录 C:\Python\Python38\Tools\pynche\__pycache__下有0个目录,0个文件 C:\Python\Python38\Tools\pynche\__pycache__ [] []
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

遍历指定目录下的文件和目录:

import os for dirpath,dirname,filenames in os.walk("C:\\Python\\Python38\\Tools\\pynche"): print(dirpath + str("(dir)")) for item in dirname: print(" |---",item + str("(dir)")) for file in filenames: print(" |---",file) 程序运行结果如下: ===================== RESTART: C:\Python\Python38\First.py ===================== C:\Python\Python38\Tools\pynche(dir) |--- X(dir) |--- __pycache__(dir) |--- ChipViewer.py |--- ColorDB.py |--- DetailsViewer.py |--- html40colors.txt |--- ListViewer.py |--- Main.py |--- namedcolors.txt |--- pyColorChooser.py |--- pynche.pyw |--- PyncheWidget.py |--- StripViewer.py |--- Switchboard.py |--- TextViewer.py |--- TypeinViewer.py |--- webcolors.txt |--- websafe.txt |--- __init__.py C:\Python\Python38\Tools\pynche\X(dir) |--- rgb.txt |--- xlicense.txt C:\Python\Python38\Tools\pynche\__pycache__(dir)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34

四、文件操作

os 模块除了可以对目录进行操作之外,还可以对文件进行一些操作。os 提供的文件操作函数如下表所示:

函数说明
access(path, accessmode)对文件是否有指定的访问权限。如果有指定的访问权限,则返回1,否则返回0。
文件的访问权限(参数 accessmode 的取值)包括:R_OK(读取)、
W_OK(写入)、X_OK(执行)或 F_OK(存在)。
chmod(path, mode)修改 path 指定的文件的访问权限。
remove(path)删除 path 指定的文件路径。
rename(src, dst)将文件或目录重命名为 dst
stat(path)返回 path 指定的文件信息
startfile(path [,operation])使用关联的应用程序打开 path 指定的文件
1、获取文件基本信息:stat() 函数

文件创建之后,文件本身会包含一些信息,比如:文件的最后一次访问时间、最后一次修改时间、文件大小等。使用 stat() 函数可以获取到文件的这些基本信息。stat() 函数的语法格式如下:

os.stat(path) 说明: (1)path:要获取文件基本信息的文件路径,可以是相对路径,也可以是绝对路径。 (2)返回值:stat() 函数的返回值是一个对象,该对象包含文件的以下属性(如下表所示)。访问这些属性可以获取文件的一些基本信息。
  • 1
  • 2
  • 3
  • 4

stat() 函数返回的对象的属性:

属性说明
st_mode保护模式
st_ino索引号
st_nlink硬连接号(被连接数据)
st_size文件大小(单位为字节)
st_mtime最后一次修改时间
st_dev设备名
st_uid用户ID
st_gid组ID
st_atime最后一次访问时间
st_ctime最后一次状态变化时间

例如:

import os st1 = os.stat("stu.txt") # 当前工作目录,文件的属性 print(type(st1)) print("文件大小:",st1.st_size,"字节") print("最后一次访问时间:",st1.st_atime) st2 = os.stat("doc") # 当前工作目录,目录的属性 print(type(st2)) print("文件大小:",st2.st_size,"字节") print("最后一次访问时间:",st2.st_atime) 程序运行结果如下: ===================== RESTART: C:\Python\Python38\First.py ===================== <class 'os.stat_result'> 文件大小: 825 最后一次访问时间: 1692429378.8944023 <class 'os.stat_result'> 文件大小: 0 最后一次访问时间: 1692429444.3054664
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
2、删除文件:remove() 函数

os 模块的 remove() 函数可以删除指定的文件。remove() 函数的语法格式如下:

os.remove(path) 说明:path 为要删除的文件路径,可以是绝对路径,也可以是相对路径。
  • 1
  • 2
  • 3

例如:

import os print(os.path.exists("aa.txt")) os.remove("aa.txt") # 删除当前工作目录下的文件 print(os.path.exists("aa.txt")) 程序运行结果如下: ===================== RESTART: C:\Python\Python38\First.py ===================== True False
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
3、重命名文件与目录:rename() 函数

使用 rename() 函数可以重命名文件与目录。如果指定的路径是文件,则重命名文件,如果指定的是目录,则重命名目录。rename() 函数的语法格式如下:

os.rename(src, dst) 说明: (1)src:指定要重命名的目录或文件。 (2)dst:指定重命名后的目录或文件。 (3)在进行文件目录的重命名时,如果指定的目录或文件不存在,将抛出异常:FileNotFoundError。因此,在进行文件或目录重命名时,应该先判断文件或目录是否存在,只有文件或目录存在时才进行重命名操作。
  • 1
  • 2
  • 3
  • 4
  • 5

例如:

import os print("目录mysoft是否存在:",os.path.exists("G:\\mysoft")) os.rename("G:\\mysoft","G:\\soft") # 重命名目录 print("目录mysoft是否存在:",os.path.exists("G:\\mysoft")) print("目录soft是否存在:",os.path.exists("G:\\soft")) print("="*40) print("文件bak.sql是否存在:",os.path.exists("G:\bak.sql")) os.rename("G:\\bak.sql","G:\\dzh.sql") # 重命名目录 print("文件bak.sql是否存在:",os.path.exists("G:\bak.sql")) print("文件dzh.sql是否存在:",os.path.exists("G:\dzh.sql")) 程序运行结果如下: ===================== RESTART: C:\Python\Python38\First.py ===================== 目录mysoft是否存在: True 目录mysoft是否存在: False 目录soft是否存在: True ======================================== 文件bak.sql是否存在: False 文件bak.sql是否存在: False 文件dzh.sql是否存在: True
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
4、分离文件名和扩展名:splitext() 函数

使用 os 模块提供的 splitext() 函数可以分离文件名与扩展名。splitext() 函数的语法格式如下:

os.path.splitext(filename) 说明:返回值为元组类型,包含两个元素,分别为文件名与扩展名。
  • 1
  • 2
  • 3

例如:

import os s = os.path.splitext("dzh.sql") print(type(s)) print(s) print("文件名为:",s[0]) print("文件扩展名为:",s[1]) 程序运行结果如下: ===================== RESTART: C:\Python\Python38\First.py ===================== <class 'tuple'> ('dzh', '.sql') 文件名为: dzh 文件扩展名为: .sql
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
5、从一个目录中提取文件名:basename() 函数

使用 os 模块提供的 basename() 函数可以把一个目录中的文件名提取出来。basename() 函数的语法格式如下:

os.path.basename(path) 说明:返回值是一个字符串。
  • 1
  • 2
  • 3

例如:

import os s = os.path.basename("C:\\Python\\Python38\\dzh.py") print(type(s)) print(s) 程序运行结果如下: ===================== RESTART: C:\Python\Python38\First.py ===================== <class 'str'> dzh.py
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
6、从一个目录中提取文件路径,不包含文件名:dirname() 函数

使用 os 模块提供的 dirname() 函数可以从一个目录中提取出文件路径。dirname() 函数的语法格式如下:

os.path.dirname(path)
  • 1

例如:

import os s = os.path.dirname("C:\\Python\\Python38\\dzh.py") print(type(s)) print(s) 程序运行结果如下: ===================== RESTART: C:\Python\Python38\First.py ===================== <class 'str'> C:\Python\Python38
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
7、判断一个目录是否为路径:isdir() 函数

使用 os 模块提供的 isdir() 函数可以判断一个目录是否为路径。isdir() 函数的语法格式如下:

os.path.isdir(path)
  • 1

例如:

import os s = os.path.isdir("C:\\Python\\Python38\\dzh.py") print(type(s)) print(s) print("="*60) s = os.path.isdir("C:\\Python\\Python38\\") print(s) 程序运行结果如下: ===================== RESTART: C:\Python\Python38\First.py ===================== <class 'bool'> False ============================================================ True
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
标签:
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

在线投稿:投稿 站长QQ:1888636

后台-插件-广告管理-内容页尾部广告(手机)
关注我们

扫一扫关注我们,了解最新精彩内容

搜索