小白进阶—python中os模块用法

时间:2023-03-10 03:51:44
小白进阶—python中os模块用法

一.os模块概述

python中的os 模块包含普遍的操作系统功能,这个模块不受平台限制,即windows和linux上都适用。

二.常用方法

1.os.name

返回正在使用的平台。如果是windows则用‘nt’表示,对于linux/unix用户则用'posix'表示。

小白进阶—python中os模块用法

2.   os.getcwd()

返回当前python脚本工作的目录路径。

小白进阶—python中os模块用法

3. os.listdir()

返回指定目录下的所有文件和目录名,括号里如果调用函数则不用双引号或单引号,如果是传入一个路径,则必须要用双引号或单引号将变量标识为一个整体,否则报错。

调用函数

小白进阶—python中os模块用法

传入参数(即路径)

小白进阶—python中os模块用法

4.os.remove()

删除一个文件,括号里必须是文件的指定路径

小白进阶—python中os模块用法

5. os.system()

运行shell命令

小白进阶—python中os模块用法

小白进阶—python中os模块用法

6. os.sep()

取代操作系统特定的路径分隔符,python是跨平台的,在windows上,文件的路径分隔符是'\'。为了让代码在不同的平台上上都能运行,使用os.sep会根据你所处的平台,自动采用相应的分隔符号。

7. os.linesep

返回当前平台使用的行终止符,Linux使用'\n', windows使用'\r\n', mac使用'\r'.

小白进阶—python中os模块用法

8. os.path.split()

返回一个路径的目录名和文件名

小白进阶—python中os模块用法

9.os.path.isfile和os.path.isdir()

函数分别检验给出的是一个路径还是目录

小白进阶—python中os模块用法

判断给出的路径是否为文件

小白进阶—python中os模块用法

判断给出的路径是否为目录

小白进阶—python中os模块用法

10. os.path.exists()

检验给出的路径是否真实存在

小白进阶—python中os模块用法

11. os.path.abspath(name)

获得绝对路径

小白进阶—python中os模块用法

12. os.path.normpath(path)

规范path字符串形式

13. os.path.getsize(name)

小白进阶—python中os模块用法

14. os.path.splitext()

分离文件名与扩展名

小白进阶—python中os模块用法

15. os.path.join(path,name)

连接目录与文件名或目录

小白进阶—python中os模块用法

16. os.path.basename(path)

返回文件名

小白进阶—python中os模块用法

17. os.path.dirname(path)

返回文件路径

小白进阶—python中os模块用法