高级文件操作
删除文件
os.remove(path)
import os
if os.path.exists(r"D:\python\demo\test.txt"): #判断文件是否存在
os.remove(r"D:\python\demo\test.txt")
重命名文件
os.rename(src,dst)
import os
scr = r"D:\python\message.txt" #原路径
dst = r"D:\python\m.txt" #修改后
if os.path.exists(scr):
os.rename(scr,dst) #重命名操作
else:
print("文件不存在。")
重命名目录
import os
scr = r"D:\python\demo" #原路径
dst = r"D:\python\demo1" #修改后
if os.path.exists(scr):
os.rename(scr,dst) #重命名操作
else:
print("目录不存在。")
获取文件基本信息
os.stat(path)
import os
fileino = os.stat("mr.png") #获取文件的基本信息
print("文件完整路径:",os.path.abspath("mr.png")) #获取文件的完整路径
#输出文件的基本信息
print("索引号:",fileinofo.st_ino)
print("设备名:",fileinfo.st_dev)
print("文件大小:",fileinfo.st_size)
print("最后一次访问时间:",fileinofo.st_atime)
print("最后一次修改时间:",fileinofo.st_mtime)
print("最后一次状态变化时间",fileinofo.st_ctime)
定义函数
def functionname([parameterlist]):
[’’‘comments’’’]
[functionbody]
自定义函数
def print_demo(): #def定义函数关键字,不调用不执行
for i in range(10):
print(“hello world”)
print_demo() #调用函数