您的位置:首页 > 编程语言 > Python开发

python笔记04-----(学习自清华大学出版社的python从入门到精通的配套视频)

2019-09-26 10:42 369 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/weixin_42035079/article/details/101426486

python笔记----文件及目录

1.基本文件操作
1.1 创建和打开文件
file = open(filename[,mode[,buffering]])
r-只读,w-只写,a-追加 与字母b组合,属于二进制模式
与+组合,可读写
file = open('status.txt,‘r’) #打开文件
file = open('status.txt,‘w’) #创建文件
file = open('status.txt,‘r’,encoding = “utf-8”) #以utf-8格式打开文件
1.2 关闭文件
file.close() #关闭文件
1.3打开文件时使用with语句
with expression as target:
with-body
with open('status.txt,‘r’,encoding = “utf-8”) as file :
pass
1.4写入文件内容
file.write(string)
file.flush() #输出缓存区
file.writelines([line + “\n” for line in list1]) #文件里写入列表,并输出换行符
1.5读取文件
1.读取指定字符
file.read([size])
file.seek([size]) #将文件指针移到到指定位置
2.读取一行
file.readline()
3.读取全部行
file.readlines() #输出字符串列表
2.目录操作
os模块:内置的与操作系统和文件系统相关的模块
2.1 os 和 os.path 模块
import os
os.name #系统名称
os.linesep #获取操作系统换行符
os.sep #获取路径符号
2.2 路径
1.相对路径
os.getcwd() #获取当前目录
2.绝对路径
os.path.absppath(相对路径) #获取绝对路径
3.拼接路径
os.path.join(path1[,path2[,…]])
2.3.判断目录是否存在
os.path.exists(path)
2.4 创建目录
os.mkdir(path,mode = 0o777)
os.mkdir(“D\demo”) #创建目录
os.makedirs(name,mode=0o777) #创建多级目录
os.makedirs(“D\demo\mr\demo\mingri”)
2.5删除目录
os.rmdir(path) #删除空目录
shutil模块
shutil.rmtree(path) #删除不为空目录
2.6遍历目录
os.walk(top(根目录)[,topdown](遍历顺序)[,onerror](错误处理方式)[,followlinks])

3.高级操作
3.1 删除文件
os.remove(path)
3.2 重命名文件和目录
os.rename(src,dst)
3.3 获取文件基本信息
os.stat(path) #返回值是一个对象
例子:
import os
def formatTime(longtime):
‘’‘格式化时间函数’’’
import time
return time.strftime("%Y-%m-%d %H:%M:%S",time.longtime(longtime))
def formatByte(number):
‘’‘格式化文件大小函数’’’
for (scale,label) in [(102410241024,“GB”), 10241024,“MB”),1024,“KB”)
if number >= scale:
return “%.2f %s” %(number1.0/scale,label)
elif number == 1:
return “1 字节“
else: #小于1kb
byte = “%.2f " %(number or 0)
return (byte[:3] if byte.endswith(”.00”) else byte) + “字节“
filleinfo = os.stat(”…") #获取文件基本信息
print("…",os.path.absppath("…") #获取文件完整路径
#输出文件基本信息
print(“索引号”,filleinfo.st_ino)
print(“设备名”,filleinfo.st_dev)
print(“文件大小”,formatByte(filleinfo.st_size))
print(“最后一次访问时间”,formatTime(filleinfo.st_atime))
print(“最后一次修改时间”,formatTime(filleinfo.st_mtime))
print(“最后一次状态变化时间”,formatTime(filleinfo.st_ctime))

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐