import os
"""
python中没有内置删除文件的函数,但是在内置的os模块中提供了删除文件的函数remove()
"""
# os.remove(r"E:\pythondaima\模块\文件及目录操作\bilibili.jpg") # 这里的r就是将\有效
"""
os模块提供了重命名文件和目录的函数rename(),如果指定的路径时文件的,则重命名文件,如果指定的路径
是目录,则重命名目录
"""
# src=r"E:\pythondaima\模块\文件及目录操作\安与骑兵1.mp3" # 要重命名的文件
# dst=r"E:\pythondaima\模块\文件及目录操作\安与骑兵.mp3" # 重命名后的文件
# if os.path.exists(src):
# os.rename(src, dst)
# print("文件重命名成功")
# else:
# print("文件不存在")
# 在使用rename()函数重命名目录时,只能修改最后一级的目录名称,否则将抛出异常
# 通过os模块的stat()函数可以获取文件的大小,最后一次访问时间等信息
#print(os.stat(r"E:\pythondaima\模块\22.jpg"))
# fileinfo=os.stat("安与骑兵.mp3") # 获取文件的基本信息
# print("文件完整路径:",os.path.abspath("安与骑兵.mp3"))
# # 输出文件的基本信息
# print("索引号:",fileinfo.st_ino)
# print("设备名:",fileinfo.st_dev)
# print("文件大小:",fileinfo.st_size,"字节")
# print("最后一次访问时间:",fileinfo.st_atime)
# print("最后一次修改时间:",fileinfo.st_mtime)
# print("最后一次状态变化时间:",fileinfo.st_ctime)
def formatTime(longtime):
"""
格式化日期时间的函数
:param longtime: 要格式化的时间
:return:
"""
import time
return time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(longtime))
def formatByte(number):
"""
格式化文件大小的函数
:param number: 要格式化的字节数
:return:
"""
for (scale,label) in [(1024*1024*1024,"GB"),(1024*1024,"MB"),(1024,"KB")]:
if number>=scale:
return "%.2f %s" %(number*1.0/scale,label)
elif number==1:
return "1字节"
else:
byte="%.2f" %(number or 0)
return (byte[:-3] if byte.endswith(".00") else byte)+"字节"
if __name__=="__main__":
fileinfo = os.stat("安与骑兵.mp3") # 获取文件的基本信息
print("文件完整路径:", os.path.abspath("安与骑兵.mp3"))
# 输出文件的基本信息
print("索引号:", fileinfo.st_ino)
print("设备名:", fileinfo.st_dev)
print("文件大小:", formatByte(fileinfo.st_size))
print("最后一次访问时间:", formatTime(fileinfo.st_atime))
print("最后一次修改时间:", formatTime(fileinfo.st_mtime))
print("最后一次状态变化时间:", fileinfo.st_ctime)