1.os模块作用
-
主要是用来完成对文件或者文件夹的操作
2.导入os模块
import os
3.listdir()
-
查看指定目录下面所有的文件或者文件夹
print(os.listdir(r"D:\PycharmProjects\pythonProject")) # ['.idea', '01_语法', '02_函数', '03_类型转换', '04_运算符', '05_分支结构', '06_循环结构', '07_字符串', '08_列表', '09_字典', '10_集合', '11_元组', '12_装饰器', '13_作用域', '14_模块']
4.curdir()
-
获取当前目录
print(os.curdir) # .
5.getcwd()
-
获取当前路径
print(os.getcwd()) # D:\PycharmProjects\pythonProject\14_模块
6.mkdir()
-
创建文件夹,不能创建已经存在的文件夹
os.mkdir(r"D:\PycharmProjects\pythonProject\15_面向对象")
7.makedirs()
-
递归式创建文件夹
os.makedirs(r"D:\PycharmProjects\pythonProject\15_面向对象\a\b\c")
8.rmdir()
-
删除文件夹,只能删除空文件夹
os.rmdir(r"D:\PycharmProjects\pythonProject\15_面向对象\a\b\c")
9.rename()
-
rename("原文件夹/文件名称", "新文件夹/文件名称") 重命名文件或文件夹
os.rename(r"D:\PycharmProjects\pythonProject\15_面向对象\a\b", r"D:\PycharmProjects\pythonProject\15_面向对象\a\bb") # 重命名文件夹
os.rename(r"D:\PycharmProjects\pythonProject\15_面向对象\a\bb\func.html", r"D:\PycharmProjects\pythonProject\15_面向对象\a\bb\hello.html") #重命名文件
10.remove()
-
删除文件
os.remove(r"D:\PycharmProjects\pythonProject\15_面向对象\a\bb\hello.html")
11.os.path.join()
-
拼接路径
print(os.path.join(r"D:\PycharmProjects\pythonProject", "笔记.md")) # D:\PycharmProjects\pythonProject\笔记.md
12.os.path.split()
-
拆分路径
print(os.path.split(r"D:\PycharmProjects\pythonProject\01_语法\01_HelloWorld.py")) # ('D:\\PycharmProjects\\pythonProject\\01_语法', '01_HelloWorld.py')
13.os.path.getsize()
-
获取文件大小
print(os.path.getsize(r"D:\PycharmProjects\pythonProject\01_语法\01_HelloWorld.py")) # 20
14.os.path.exists()
-
判断文件是否存在,若存在返回True,若不存在返回False
print(os.path.exists(r"D:\PycharmProjects\pythonProject\01_语法\01_HelloWorld.py")) # True
print(os.path.exists(r"D:\PycharmProjects\pythonProject\笔记.md")) # False
15.os.path.isfile()
-
判断是否是文件,若是返回True,若不是返回False
print(os.path.isfile(r"D:\PycharmProjects\pythonProject\01_语法\01_HelloWorld.py")) # True
print(os.path.isfile(r"D:\PycharmProjects\pythonProject")) # False
16.os.path.isdir()
-
判断是否是文件夹,若是返回True,若不是返回False
print(os.path.isdir(r"D:\PycharmProjects\pythonProject")) # True
print(os.path.isdir(r"D:\PycharmProjects\pythonProject\01_语法\01_HelloWorld.py")) # False