集合
集合是无序的,不重复的数据集合,它里面的元素是可哈希的(不可变类型),但是集合本身是不可哈希(所以集合做不了字典的键)的。以下是集合最重要的两点:
去重,把一个列表变成集合,就自动去重了。
关系测试,测试两组数据之前的交集、差集、并集等关系。
集合的创建
set1 = set({1, 2, ‘abc‘}) set2 = {1, 2, ‘asd‘} print(set1, type(set1)) print(set2, type(set2)) #输出:{1, 2, ‘abc‘} <class ‘set‘> {‘asd‘, 1, 2} <class ‘set‘>
集合的元素增加
set1={1,2,3,4,5,‘abc‘,‘efg‘,‘asd‘} set1.add(‘半江‘) print(set1) #输出:{‘半江‘, 1, 2, 3, 4, 5, ‘abc‘, ‘efg‘, ‘asd‘} #update迭代着加 set1={1,2,3,‘abc‘,‘efg‘} set1.update(‘abc‘) print(set1)
set1={1,2,3,‘abc‘,‘efg‘}
set1.update(‘d4h‘)
print(set1)
#输出:{‘h‘, 1, 2, 3, ‘abc‘, ‘4‘, ‘d‘, ‘efg‘}
set1={1,2,3,‘abc‘,‘efg‘} set1.update([6,1,8]) print(set1) #输出:{1, 2, 3, ‘abc‘, 6, 8, ‘efg‘}
集合元素删除
set1={1,2,3,‘abc‘,‘efg‘} set1.remove(‘abc‘) #删除一个指定元素 print(set1) #输出:{1, 2, 3, ‘efg‘} set1={1,2,3,‘abc‘,‘efg‘} set1.pop() #随机删除一个元素 print(set1) #输出:{2, 3, ‘efg‘, ‘abc‘} set1={1,2,3,‘abc‘,‘efg‘} set1.clear() #清空集合 print(set1) #输出:set() set1={1,2,3,‘abc‘,‘efg‘} del set1 #删除集合 print(set1)
集合的其他操作
交集 (& 或者 intersection)
set1 = {1,2,3,4,5} set2 = {4,5,6,7,8} print(set1 & set2) # {4, 5} print(set1.intersection(set2)) # {4, 5}
并集 (| 或者 union)
set1 = {1,2,3,4,5} set2 = {4,5,6,7,8} print(set1 | set2) # {1, 2, 3, 4, 5, 6, 7} print(set2.union(set1)) # {1, 2, 3, 4, 5, 6, 7}
差集 (- 或者 difference)
set1 = {1,2,3,4,5} set2 = {4,5,6,7,8} print(set1 - set2) # {1, 2, 3} print(set1.difference(set2)) # {1, 2, 3}
反交集 (^ 或者 symmetric_difference)
set1 = {1,2,3,4,5} set2 = {4,5,6,7,8} print(set1 ^ set2) # {1, 2, 3, 6, 7, 8} print(set1.symmetric_difference(set2)) # {1, 2, 3, 6, 7, 8}
子集与超集
set1 = {1,2,3} set2 = {1,2,3,4,5,6} print(set1 < set2) print(set1.issubset(set2)) print(set2 > set1) print(set2.issuperset(set1))
frozenset 函数把集合变成不可变集合
set1={1,2,3,‘abc‘,‘efg‘} set2=frozenset(set1) print(set2,type(set2)) #输出:frozenset({1, 2, 3, ‘abc‘, ‘efg‘}) <class ‘frozenset‘>
文件操作
读写文件是常用的操作,Python内置了读写文件的函数。读写文件前,我们先必须了解一下,在磁盘上读写文件的功能都是由操作系统提供的,现代操作系统不允许普通的程序直接操作磁盘,所以,读写文件就是请求操作系统打开一个文件对象(通常称为文件描述符),然后,通过操作系统提供的接口从这个文件对象中读取数据(读文件),或者把数据写入这个文件对象(写文件)。
打开文件
#打开文件,这里的路径分绝对路径和相对路径。相对路径就是指由这个文件所在的路径引起的跟其它文件(或文件夹)的路径关系。open是windows下的系统命令 f=open(‘文件路径‘,encoding=‘编码方式‘,‘打开方式‘) #默认打开方式是r,编码方式要和要打开的文件的编码方式一样,如果不写编码方式,
则操作系统选择默认方式打开文件,在windows下是gbk,在linux下是utf-8 #这里的 f 是句柄,可以通过句柄对文件进行操作 data=f.read() #关闭文件,释放内存 f.close()
读写文件
读文件分为 r 和 rb ,rb一般用于文件的上传和下载和对非文字类型的文件操作,如图片、视频等。
第一种读取方法:f.read() 全部读出来
f=open(‘book.txt‘,mode=‘r‘,encoding=‘utf-8‘) b=f.read() #全部读取出来 print(b) f.close()
第二种读取方法: f.read(n) 按照字符或者字节 n 读
f=open(‘book.txt‘,mode=‘r‘,encoding=‘utf-8‘) b=f.read(10) # f.read(n),按照字符读取,读取前n个字符 print(b) f.close()
f=open(‘book.txt‘,mode=‘rb‘) #这里不能填编码方式,因为rb十二进制模式
print(f.read(6)) #f.read(n)这里是按照字节 n 来读的
f.close()
Ps:把str变成byte类型和将byte类型变成str类型
a=‘sanliang半江‘
b=a.encode(‘utf-8‘)
print(b)
s=b‘sanliang\xe5\x8d\x8a\xe6\xb1\x9f‘.decode(‘utf-8‘)
print(s)
#输出:
b‘sanliang\xe5\x8d\x8a\xe6\xb1\x9f‘
sanliang半江
第三种方法:f.readline() 按行读
f = open(‘book.txt‘, encoding=‘utf-8‘, mode=‘r‘) line1 = f.readline() #读第一行的内容 print(line1) line2 = f.readline() #读第二行的内容 print(line2) f.close()
第四种方法:f.readlines() 每一行作为一个元素放在列表中
f = open(‘book.txt‘, encoding=‘utf-8‘, mode=‘r‘) lines = f.readlines() print(lines) f.close() #输出:[‘第一行\n‘, ‘第二行\n‘, ‘第三行‘]
第五种方法:循环读取 推荐使用此方法
f = open(‘book.txt‘, encoding=‘utf-8‘, mode=‘r‘) for i in f: #这里循环得到文件的每一行作为 i print(i) f.close() #输出:
第一行 第二行 第三行
写文件 w :如果没有文件则创建该文件,如果有则将原文件内容全部删除再将新内容写入
f = open(‘book.txt‘, encoding=‘utf-8‘, mode=‘w‘) #有book.txt则删除内容再写入,没有则创建该文件写入 f.write(‘三两半江‘) f.close()
对于wb来说,是写入bytes 类型的数据进文件
f = open(‘book.txt‘, mode=‘wb‘) f.write(‘三两半江‘.encode(‘utf-8‘)) f.close()
追加 a ,ab
f = open(‘book.txt‘,encoding=‘utf-8‘,mode=‘a‘) f.write(‘abc‘) #在原文件的所有内容的后面加入‘abc’ f.close()
读写 r+ (先读后写) ,下面代码先把book.txt的内容读取出来,再在里面全部内容的最后追加‘abc’
f = open(‘book.txt‘,encoding=‘utf-8‘,mode=‘r+‘) print(f.read()) f.write(‘abc‘) f.close()
写读 w+ (先写后读)
f = open(‘book.txt‘,encoding=‘utf-8‘,mode=‘w+‘) f.write(‘abc‘) f.seek(0) #这一句涌来移动光标到开头,不然光标在最后读取不出任何内容 print(f.read()) f.close() #代码的作用是将book.txt的所有内容删除,添加‘abc‘进去,然后把光标移到开头,读出‘abc’
写读 a+
文件操作方法
常用操作方法
read(3):
1. 文件打开方式为文本模式时,代表读取3个字符
2. 文件打开方式为b模式时,代表读取3个字节
其余的文件内光标移动都是以字节为单位的如:seek,tell,truncate
注意:
1. seek有三种移动方式0,1,2,其中1和2必须在b模式下进行,但无论哪种模式,都是以bytes为单位移动的
2. truncate是截断文件,所以文件的打开方式必须可写,但是不能用w或w+等方式打开,因为那样直接清空文件了,所以truncate要在r+或a或a+等模式下测试效果。
操作方法:
class file(object) def close(self): # real signature unknown; restored from __doc__ 关闭文件 def fileno(self): # real signature unknown; restored from __doc__ 文件描述符 """ fileno() -> integer "file descriptor". This is needed for lower-level file interfaces, such os.read(). """ return 0 def flush(self): # real signature unknown; restored from __doc__ 刷新文件内部缓冲区 """ flush() -> None. Flush the internal I/O buffer. """ pass def isatty(self): # real signature unknown; restored from __doc__ 判断文件是否是同意tty设备 """ isatty() -> true or false. True if the file is connected to a tty device. """ return False def next(self): # real signature unknown; restored from __doc__ 获取下一行数据,不存在,则报错 """ x.next() -> the next value, or raise StopIteration """ pass def read(self, size=None): # real signature unknown; restored from __doc__ 读取指定字节数据 """ read([size]) -> read at most size bytes, returned as a string. If the size argument is negative or omitted, read until EOF is reached. Notice that when in non-blocking mode, less data than what was requested may be returned, even if no size parameter was given. """ pass def readinto(self): # real signature unknown; restored from __doc__ 读取到缓冲区,不要用,将被遗弃 """ readinto() -> Undocumented. Don‘t use this; it may go away. """ pass def readline(self, size=None): # real signature unknown; restored from __doc__ 仅读取一行数据 """ readline([size]) -> next line from the file, as a string. Retain newline. A non-negative size argument limits the maximum number of bytes to return (an incomplete line may be returned then). Return an empty string at EOF. """ pass def readlines(self, size=None): # real signature unknown; restored from __doc__ 读取所有数据,并根据换行保存值列表 """ readlines([size]) -> list of strings, each a line from the file. Call readline() repeatedly and return a list of the lines so read. The optional size argument, if given, is an approximate bound on the total number of bytes in the lines returned. """ return [] def seek(self, offset, whence=None): # real signature unknown; restored from __doc__ 指定文件中指针位置 """ seek(offset[, whence]) -> None. Move to new file position. Argument offset is a byte count. Optional argument whence defaults to (offset from start of file, offset should be >= 0); other values are 1 (move relative to current position, positive or negative), and 2 (move relative to end of file, usually negative, although many platforms allow seeking beyond the end of a file). If the file is opened in text mode, only offsets returned by tell() are legal. Use of other offsets causes undefined behavior. Note that not all file objects are seekable. """ pass def tell(self): # real signature unknown; restored from __doc__ 获取当前指针位置 """ tell() -> current file position, an integer (may be a long integer). """ pass def truncate(self, size=None): # real signature unknown; restored from __doc__ 截断数据,仅保留指定之前数据 """ truncate([size]) -> None. Truncate the file to at most size bytes. Size defaults to the current file position, as returned by tell(). """ pass def write(self, p_str): # real signature unknown; restored from __doc__ 写内容 """ write(str) -> None. Write string str to file. Note that due to buffering, flush() or close() may be needed before the file on disk reflects the data written. """ pass def writelines(self, sequence_of_strings): # real signature unknown; restored from __doc__ 将一个字符串列表写入文件 """ writelines(sequence_of_strings) -> None. Write the strings to the file. Note that newlines are not added. The sequence can be any iterable object producing strings. This is equivalent to calling write() for each string. """ pass def xreadlines(self): # real signature unknown; restored from __doc__ 可用于逐行读取文件,非全部 """ xreadlines() -> returns self. For backward compatibility. File objects now include the performance optimizations previously implemented in the xreadlines module. """ pass
def close(self, *args, **kwargs): # real signature unknown 关闭文件 pass def fileno(self, *args, **kwargs): # real signature unknown 文件描述符 pass def flush(self, *args, **kwargs): # real signature unknown 刷新文件内部缓冲区 pass def isatty(self, *args, **kwargs): # real signature unknown 判断文件是否是同意tty设备 pass def read(self, *args, **kwargs): # real signature unknown 读取指定字节数据 pass def readable(self, *args, **kwargs): # real signature unknown 是否可读 pass def readline(self, *args, **kwargs): # real signature unknown 仅读取一行数据 pass def seek(self, *args, **kwargs): # real signature unknown 指定文件中指针位置 pass def seekable(self, *args, **kwargs): # real signature unknown 指针是否可操作 pass def tell(self, *args, **kwargs): # real signature unknown 获取指针位置 pass def truncate(self, *args, **kwargs): # real signature unknown 截断数据,仅保留指定之前数据 pass def writable(self, *args, **kwargs): # real signature unknown 是否可写 pass def write(self, *args, **kwargs): # real signature unknown 写内容 pass def __getstate__(self, *args, **kwargs): # real signature unknown pass def __init__(self, *args, **kwargs): # real signature unknown pass @staticmethod # known case of __new__ def __new__(*args, **kwargs): # real signature unknown """ Create and return a new object. See help(type) for accurate signature. """ pass def __next__(self, *args, **kwargs): # real signature unknown """ Implement next(self). """ pass def __repr__(self, *args, **kwargs): # real signature unknown """ Return repr(self). """ pass buffer = property(lambda self: object(), lambda self, v: None, lambda self: None) # default closed = property(lambda self: object(), lambda self, v: None, lambda self: None) # default encoding = property(lambda self: object(), lambda self, v: None, lambda self: None) # default errors = property(lambda self: object(), lambda self, v: None, lambda self: None) # default line_buffering = property(lambda self: object(), lambda self, v: None, lambda self: None) # default name = property(lambda self: object(), lambda self, v: None, lambda self: None) # default newlines = property(lambda self: object(), lambda self, v: None, lambda self: None) # default _CHUNK_SIZE = property(lambda self: object(), lambda self, v: None, lambda self: None) # default _finalizing = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
文件的修改
文件的数据是存放于硬盘上的,因而只存在覆盖、不存在修改这么一说,我们平时看到的修改文件,都是模拟出来的效果。
改动文件的内部步骤:
1)创建一个新文件,
2)读取原文件,
import os
# with open(‘log‘,encoding=‘utf-8‘) as f1,\
# open(‘log.bak‘,‘w‘,encoding=‘utf-8‘) as f2:
3)更改文件内容并写入新文件,原文件不变,
old_content = f1.read()
# new_content = old_content.replace(‘alex‘,‘SB‘)
# f2.write(new_content)
4)将原文件删除,
os.remove(‘log‘)
5)将新文件命名为原文件。
os.rename(‘log.bak‘,‘log‘)
方法一:将硬盘存放的该文件的内容全部加载到内存,在内存中是可以修改的,修改完毕后,再由内存覆盖到硬盘(word,vim,nodpad++等编辑器)
import os # 调用系统模块 with open(‘a.txt‘) as read_f,open(‘.a.txt.swap‘,‘w‘) as write_f: data=read_f.read() #全部读入内存,如果文件很大,会很卡 data=data.replace(‘alex‘,‘SB‘) #在内存中完成修改 write_f.write(data) #一次性写入新文件 os.remove(‘a.txt‘) #删除原文件 os.rename(‘.a.txt.swap‘,‘a.txt‘) #将新建的文件重命名为原文件
方法二:方式二:将硬盘存放的该文件的内容一行一行地读入内存,修改完毕就写入新文件,最后用新文件覆盖源文件
import os with open(‘a.txt‘) as read_f,open(‘.a.txt.swap‘,‘w‘) as write_f: for line in read_f: line=line.replace(‘alex‘,‘SB‘) write_f.write(line) os.remove(‘a.txt‘) os.rename(‘.a.txt.swap‘,‘a.txt‘)
Ps:python为了解决忘写f.close()语句的问题,加入了with语句
with open(‘log‘,‘r‘,encoding=‘utf-8‘) as f1, open(‘log1‘,‘r‘,encoding=‘utf-8‘) as f2: print(f1.read()) print(f2.read())