文件处理file handling

家住魔仙堡 提交于 2020-01-26 03:13:29
#1. 打开文件,得到文件句柄并赋值给一个变量
#2. 通过句柄对文件进行操作
#3. 关闭文件
#1、open函数打开文件,open找的是系统的编码gbkf = open("陈粒",encoding="utf-8") #打开文件指定编码data = f.read() #读的模式print(data)f.close()   #关闭文件f = open("xxx")data = f.read()print(data)f.close()#2、r是读的方式,readable是判断是否可读f = open("陈粒","r",encoding="utf-8")print(f.readable()) ##3、readline默认一次读取一行f = open("陈粒",encoding="utf-8")print("第一行",f.readline(),end="")print("第二行",f.readline(),end="")print("第三行",f.readline(),end="")print("第四行",f.readline(),end="")print("第五行",f.readline(),end="")print("第六行",f.readline(),end="")print("第七行",f.readline(),end="")f.close()print("读的模式已结束")#4、写模式只能写不能读、读模式只能读不能写#5、w模式是把文件内容清空掉再执行操作如果文件不存在的话再重新新建一个文件f = open("陈粒1","w",encoding="utf-8")f.write("11111\n")f.write("22222\n")f.write("33333\n")f.write("44444\n")  #\n回车加换行f.writelines(["555\n","666\n"])f.close()print("写的模式已结束")#6、writable判断是否可写#7、writelines写入行#8、追加模式用af = open("陈粒1","a",encoding="utf-8")f.write("写到最后")f.close()print("追加模式已结束了了了了了了了了了了了了了了了了了了了了了了了了了了了了了了了了了了了了了了了了了了了了了")#9、r+读写模式f = open("xxx","r+",encoding="utf-8")data = f.read()print(data)f.write("123")f.close()#10、r读的方式打开文件,w写的方式到新文件src_f = open("xxx","r",encoding= "utf-8")data = src_f.readlines()src_f.close()print(data)dst_f = open("xxx_new","w",encoding="utf-8")dst_f.write(data[0])dst_f.close()#11、with用法一:with open("a.txt","w") as f:    f.write("1111\n")#12、with用法二:# src_f = open("xxx","r",encoding="utf-8")# dst_f = open("xxx","w",encoding="utf-8")with open("xxx","r",encoding="utf-8") as src_f,\        open("xxx_new","w",encoding="utf-8") as dst_f:    data = src_f.read()    dst_f.write(data)

#13、l = [1,2,3,4,5]print(list(map(str,l)))#14、from functools import reducel = [1,2,3,4,5]print(reduce(lambda x,y : x + y,l,3))#15、过滤下划线_xx的元素name = ["zd_xx","zs"]a = filter(lambda x:not x.endswith("_xx"),name)print(list(a))#16、map函数是对每个元素处理返回同等元素,filter函数是过滤每个元素返回过滤的结果,reduce函数是对很多个元素处理返回一个元素#17、r模式读、a模式追加、w模式覆盖并追加#18、b方式以字节的方式操作#f = open("test11.py","rb",encoding="utf-8")f = open("test11.py","rb")data = f.read()print(data) #结果是字节形式print(data.decode("utf-8"))# 把二进制转成字符串形式#19、windows平台中\r\n是回车的意思,Linux平台中回车是\n#20、"字符串"----------------encode-------------》bytes#21、"bytes"----------------decode-------------》字符串#22、wb是二进制方式#23、把字符串转换成bytes类型x ="hello"print(bytes(x,encoding="utf-8"))#24、把字符串转换成二进制是编码的过程a = "张达".encode("utf-8")print(a)#25、closed判断文件状态是否关闭f = open("a.txt","w")print(f.closed)#26、encoding取自文件打开的编码print(f.encoding)#27、cp936是gbk的#28、latin-1拉丁编码f = open("a.txt","r+",encoding="utf-8")print(f.readlines())print("结束了")#29、flush刷新#30、tell光标读取print(f.tell())f.readline()print(f.tell())#31、seek控制光标移动#32、f.seek(3)print(f.read())#33、truncate截断print("上面的已结束")#34、f = open("seek.txt","r",encoding="utf-8")print(f.tell())f.seek(10)print(f.tell())f.seek(3)print(f.tell())
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!