一,创建, 删除文件
os.mkdir("test")
os.rename("test","test1")
os.rmdir("test")
二,获取目录
import os
print("os.curdir =",os.curdir)
>>>os.curdir = .
print("os.getcwd() =",os.getcwd())
print(os.path.abspath(os.path.dirname(__file__)))
>>>os.getcwd() = D:\test\MyPython\selfStudy\qianfeng_teach\System
print("os.listdir() =",os.listdir())
>>>os.listdir() = ['TestOS.py', '__init__.py']
print(os.path.abspath(os.path.dirname(os.path.dirname(__file__))))
print(os.path.abspath(os.path.join(os.getcwd(), "..")))
print(os.path.abspath(os.path.join(os.getcwd(), "../..")))
三,删除文件
with open("test.txt","w") as file:
file.write("test")
file.close()
os.remove("test.txt")
四,执行DOS命令
system 输入cmd命令行功能
os.system("shut down -s -t 500")
os.system("mspaint")
os.system("taskkill /f /im mspaint.exe")
五,os.path 模块的方法
print(os.path.abspath("."))
>>>D:\test\MyPython\selfStudy\qianfeng_teach\System
CurrentPath = os.getcwd()
CurrentPath1 = r"D:\test\MyPython\selfStudy\qianfeng_teach\System1"
print(CurrentPath)
>>>D:\test\MyPython\selfStudy\qianfeng_teach\System
print(os.path.split(CurrentPath))
>>>('D:\\test\\MyPython\\selfStudy\\qianfeng_teach', 'System')
FilePath = r"D:\test\MyPython\selfStudy\qianfeng_teach\System\TestOS.py"
FilePath1 = r"D:\test\MyPython\selfStudy\qianfeng_teach\System\TestOS1.py"
print(os.path.split(FilePath))
>>>('D:\\test\\MyPython\\selfStudy\\qianfeng_teach\\System', 'TestOS.py')
print(os.path.splitext(FilePath))
>>>('D:\\test\\MyPython\\selfStudy\\qianfeng_teach\\System\\TestOS', '.py')
print(os.path.splitext(CurrentPath))
>>>('D:\\test\\MyPython\\selfStudy\\qianfeng_teach\\System', '')
print(os.path.isdir(CurrentPath))
>>>True
print(os.path.isfile(FilePath))
>>>True
print(os.path.exists(FilePath1))
>>>False
print(os.path.getsize(FilePath))
>>>2122