day5(Alex python)

版权声明:本文为博主原创文章,转载请注明作者和出处。https://blog.csdn.net/xq920831/article/details/82143524

今天学习了集合的一些操作,文件的操作。

代码如下:

1. 集合的操作

# -*- coding:utf-8 -*-
# Author: Agent Xu

list = [1,2,3,3,4,4,5,5,6,6]
#列表内容去重,把列表变为集合,集合也是无序的
list = set(list)
print(list,type(list))
#{1, 2, 3, 4, 5, 6} <class 'set'>

list_1 = set([1,2,3,4,5,6])
list_2 = set([4,5,6,7,8,9])

#交集
print(list_1.intersection(list_2))
#{4, 5, 6}
#或者用运算符号
print(list_1 & list_2)

#并集
print(list_1.union(list_2))
print(list_1 | list_2)
#{1, 2, 3, 4, 5, 6, 7, 8, 9}

#差集
print(list_1.difference(list_2))
print(list_1 - list_2)
#{1, 2, 3}
print(list_2.difference(list_1))
print(list_2 - list_1)
#{8, 9, 7}

#判断是否为子集
print(list_1.issubset(list_2))
#False
#判断是否为父集
print(list_1.issuperset(list_2))
#False

#对称差集:把共同的部分去掉,再取并集。
print(list_1.symmetric_difference(list_2))
print(list_1 ^ list_2)
#{1, 2, 3, 7, 8, 9}

#如果两个集合的交集为空,返回True
print(list_1.isdisjoint(list_2))
#False

#添加
list_1.add(18)
print(list_1)
#{1, 2, 3, 4, 5, 6, 18}

#添加多项
list_2.update([12,16,20])
print(list_2)
#{4, 5, 6, 7, 8, 9, 12, 16, 20}

#删除
list_1.remove(18)
print(list_1)
#{1, 2, 3, 4, 5, 6}

#长度
print(len(list_1))
#6

#discard删除一个在集合中的元素,如果不在则什么也不做(remove会报错)
list_1.discard(111)


2. 文件的操作

# -*- coding:utf-8 -*-
# Author: Agent Xu

#读取文件内容并打印
data = open('file1.txt','r').read()
print(data)

#写文件(保留原文件内容)
f = open('file1.txt','a') #文件句柄
f.write('\nafdarrwarawra')
f.write('\nqwinqwiedww')

#关闭文件
f.close()

#按行读取文件内容
f = open('file1.txt','r') #文件句柄

#读取前五行
for i in range(5):
    print(f.readline().strip())  #.strip是把换行符去掉

#按行读取文件所有内容
for line in f.readlines():
    print(line.strip())

#最有效简便的读取方法#  一行行读,且内存中只保留一行的数据,不浪费内存
for line in f:
    print(line.strip())

#显示读取的位置(字符个数)
ff = open('file1.txt','r',encoding='utf-8')
print(ff.tell())
#0
print(ff.readline().strip())
#afdarrwarawra
print(ff.tell())
#16
print(ff.read(10)) #read为读取字符个数
#qwinqwiedw

ff.seek(0)#读取光标返回开头

print(ff.encoding) #打印文件的编码
#utf-8

#截断
w = open('file1.txt','a',encoding='utf-8')
w.seek(2)  #如不指定开始,则从0开始
w.truncate(10)  #结尾

附一张文件操作的模式:

最后附上一个进度条小程序:

# -*- coding:utf-8 -*-
# Author: Agent Xu

#每间隔1秒打印一个#字符,一共30个#字符
#主要想说明两点:1.flush函数的作用(用于刷新)2.stdout.write函数输出不会换行
import sys,time

for i in range(30):
    sys.stdout.write('#')
    sys.stdout.flush()
    time.sleep(1)

今天就到这里。。。。

猜你喜欢

转载自blog.csdn.net/xq920831/article/details/82143524