python基础_集合文件操作
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python基础_集合文件操作相关的知识,希望对你有一定的参考价值。
集合
集合是一个无序的且数据不会重复。有去重、关系测试的作用
list = ["11","22","33","44","55"] list = set(list) print(list,type(list)) 结果为: {‘33‘, ‘11‘, ‘22‘, ‘55‘, ‘44‘} <class ‘set‘>
关系测试
list1 = set(["11","22","33","44","55"]) list2 = set(["55","66","77","88","99"]) list3 = set(["11","22"]) #list = set(list) print(list1,type(list)) #交集 print(list1.intersection(list2)) #并集 print(list1.union(list2)) #差集 print(list1.difference(list2))#list1 有,list2没有 #子集 print(list1.issubset(list2))# False print(list3.issubset((list1))) #True
print(list1.isdisjoint(list2))#没有交集
#反相差集 print(list1.symmetric_difference(list2))#把不是交集部分取出 结果为: {‘55‘, ‘44‘, ‘11‘, ‘22‘, ‘33‘} <class ‘type‘> {‘55‘} {‘11‘, ‘22‘, ‘66‘, ‘44‘, ‘33‘, ‘88‘, ‘77‘, ‘99‘, ‘55‘} {‘44‘, ‘11‘, ‘22‘, ‘33‘} False True {‘11‘, ‘66‘, ‘22‘, ‘33‘, ‘88‘, ‘77‘, ‘99‘, ‘44‘}
文件操作
f = open("test","r",encoding= "utf-8") data = f.read() data2 = f.read() print(data) print("-----data2-----%s"%data)
f = open("test","w",encoding= "utf-8") f.write("北京") f.write("天安门")
f1 = open("test","a",encoding="utf-8")#追加,只能写 f1.write("lalala")
f = open ("test","r",encoding="utf-8") print(f.readline()) print(f.readline()) print(f.readline())#按行读 或 f = open ("test","r",encoding="utf-8") for i in range(5): print(f.readline())#按行读
f = open ("test","r",encoding="utf-8") print(f.readlines())#每行为一个元素,打印出整个列表 结果: [‘第一句话北京天安门lalala\\n‘, ‘第二句呼啦啦哗啦啦\\n‘, ‘第三句规定不到佛‘] f = open ("test","r",encoding="utf-8") for i in f.readlines():#打印出每一行的元素,就是打印整个文件 print(i)
f = open ("test","r",encoding="utf-8") for i in f:#一行行的读,读完并释放内存,高效 print(i) f = open ("test","r",encoding="utf-8") for index,line in enumerate(f.readlines()):#将文件转换成列表 if index == 1: print("跳过") else: print(line)
f = open ("test","r",encoding="utf-8") print(f.readline(),"读到第一行") print(f.read())#从第二行读取 f.seek(0) #光标移回第一行,可重新开始读 print(f.read())
其他方法 encoding f = open ("test","r",encoding="utf-8") print(f.encoding)#打印文件的编码 fileno f = open ("test","r",encoding="utf-8") print(f.fileno())#文件句柄在操作系统的编号 f = open ("test","r",encoding="utf-8") print(f.isatty())#判断是不是终端设备
f = open("test","r+",encoding="utf-8")#读和追加模式 print(f.readline()) f.write("\\n******") print(f.readline())
f = open("test","w+",encoding="utf-8")#写读,先创建文件 f.write("******\\n") f.write("******\\n") f.write("******\\n") f.write("******\\n") print(f.readline()) print(f.tell()) f.write("1******") print(f.readline())
f = open("test","rb")#以二进制去读,不要添加,encoding="utf-8" print(f.readline())
f = open("test","wb")#以二进制去读,不要添加,encoding="utf-8" f.write("噜啦噜啦啦欧拉".encode())
文件替换
#with with open("test","r",encoding="utf-8") as f: print(f.readline()) for line in f: print(line.strip())
#打开多个文件
with open("test","r",encoding="utf-8") as f,\\
open("test","r",encoding="utf-8"):
以上是关于python基础_集合文件操作的主要内容,如果未能解决你的问题,请参考以下文章