Python基础:集合与文件操作
集合
集合是无序的,不重复的数据集合,它里面的元素是可哈希的(不可变类型),但是集合本身是不可哈希(所以集合做不了字典的键)的。以下是集合最重要的两点:
去重,把一个列表变成集合,就自动去重了。
关系测试,测试两组数据之前的交集、差集、并集等关系。
集合的创建
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: #这里循环得到文件的每一行作为 iprint(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. """passdef isatty(self): # real signature unknown; restored from __doc__ 判断文件是否是同意tty设备""" isatty() -> true or false. True if the file is connected to a tty device. """return Falsedef next(self): # real signature unknown; restored from __doc__ 获取下一行数据,不存在,则报错""" x.next() -> the next value, or raise StopIteration """passdef 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 requestedmay be returned, even if no size parameter was given."""passdef readinto(self): # real signature unknown; restored from __doc__ 读取到缓冲区,不要用,将被遗弃""" readinto() -> Undocumented. Don't use this; it may go away. """passdef 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 maximumnumber of bytes to return (an incomplete line may be returned then).Return an empty string at EOF."""passdef 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 thetotal 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 (moverelative to end of file, usually negative, although many platforms allowseeking 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 causesundefined behavior.Note that not all file objects are seekable."""passdef tell(self): # real signature unknown; restored from __doc__ 获取当前指针位置""" tell() -> current file position, an integer (may be a long integer). """passdef 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()."""passdef 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 beforethe file on disk reflects the data written."""passdef 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 objectproducing strings. This is equivalent to calling write() for each string."""passdef xreadlines(self): # real signature unknown; restored from __doc__ 可用于逐行读取文件,非全部"""xreadlines() -> returns self.For backward compatibility. File objects now include the performanceoptimizations previously implemented in the xreadlines module."""pass
Python2.x
def close(self, *args, **kwargs): # real signature unknown 关闭文件passdef fileno(self, *args, **kwargs): # real signature unknown 文件描述符 passdef flush(self, *args, **kwargs): # real signature unknown 刷新文件内部缓冲区passdef isatty(self, *args, **kwargs): # real signature unknown 判断文件是否是同意tty设备passdef read(self, *args, **kwargs): # real signature unknown 读取指定字节数据passdef readable(self, *args, **kwargs): # real signature unknown 是否可读passdef readline(self, *args, **kwargs): # real signature unknown 仅读取一行数据passdef seek(self, *args, **kwargs): # real signature unknown 指定文件中指针位置passdef seekable(self, *args, **kwargs): # real signature unknown 指针是否可操作passdef tell(self, *args, **kwargs): # real signature unknown 获取指针位置passdef truncate(self, *args, **kwargs): # real signature unknown 截断数据,仅保留指定之前数据passdef writable(self, *args, **kwargs): # real signature unknown 是否可写passdef write(self, *args, **kwargs): # real signature unknown 写内容passdef __getstate__(self, *args, **kwargs): # real signature unknownpassdef __init__(self, *args, **kwargs): # real signature unknownpass@staticmethod # known case of __new__def __new__(*args, **kwargs): # real signature unknown""" Create and return a new object. See help(type) for accurate signature. """passdef __next__(self, *args, **kwargs): # real signature unknown""" Implement next(self). """passdef __repr__(self, *args, **kwargs): # real signature unknown""" Return repr(self). """passbuffer = 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
Python3.x
文件的修改
文件的数据是存放于硬盘上的,因而只存在覆盖、不存在修改这么一说,我们平时看到的修改文件,都是模拟出来的效果。
改动文件的内部步骤:
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') #将新建的文件重命名为原文件
View Code
方法二:方式二:将硬盘存放的该文件的内容一行一行地读入内存,修改完毕就写入新文件,最后用新文件覆盖源文件
import oswith 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')
View Code
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())
转载于:https://www.cnblogs.com/banjiang/p/8386924.html
Python基础:集合与文件操作相关推荐
- 第三章:Python基础の函数和文件操作实战
本課主題 Set 集合和操作实战 函数介紹和操作实战 参数的深入介绍和操作实战 format 函数操作实战 lambda 表达式介绍 文件操作函数介紹和操作实战 本周作业 Set 集合和操作实战 Se ...
- python基础3之文件操作、字符编码解码、函数介绍
内容概要: 一.文件操作 二.字符编码解码 三.函数介绍 一.文件操作 文件操作流程: 打开文件,得到文件句柄并赋值给一个变量 通过句柄对文件进行操作 关闭文件 基本操作: 1 #/usr/bin/e ...
- Python基础7:文件操作
[ 文件操作] 1 对文件操作流程 打开文件,得到文件句柄并赋值给一个变量 通过句柄对文件进行操作 关闭文件 现有文件如下: 昨夜寒蛩不住鸣. 惊回千里梦,已三更. 起来独自绕阶行. 人悄悄,帘外月胧 ...
- Python基础知识_day10_文件操作_pickle模块_os模块_shutil模块
文章目录 1. 文本文件和二进制文件 2. 创建文件对象 open() 3. 文本文件的写入 3.1 write()/writelines()写入数据 3.2 with语句 4. 文本文件的读取 5. ...
- 简单 Python 快乐之旅之:Python 基础语法之文件操作专题
文章目录 1. 读取文本文件 1.1. 读取文本文件里的个别字符 1.2. 以文本模式读取文件 2. 向文本文件写入字符串 2.1. 将字符串写入文本文件 2.2. 在文本模式下将字符串写入文本文件 ...
- python基础之写文件操作
博主简介:原互联网大厂tencent员工,网安巨头Venustech员工,阿里云开发社区专家博主,微信公众号java基础笔记优质创作者,csdn优质创作博主,创业者,知识共享者,欢迎关注,点赞,收藏. ...
- Python基础 2.1 文件操作
2.1 文件 文章目录 2.1 文件 2.1.1 文件的打开和关闭 1.文件的操作流程 2.打开文件 2.关闭文件 3.自动关闭文件(记忆) 2.1.2 文件的读写操作 1.文件的写操作 2.文件的读 ...
- Python基础_09:文件操作
文章目录 文件概念和作用 文件类型 文件操作流程 文件读取方式 文件写入方式 Tips: 文件其他方法 文件复制 补充部分 文件指针 f.seek()应用 修改文件的两种方式: 文件概念和作用 什么是 ...
- python基础一 day6 文件操作
读写只会进行两步, r+模式下写读 seek是按字节去找的 for line in f: for循环是一行一行的读取出来 strip默认去空格和换行符 空格.制表符.换行符.回车.换页垂直制表符和换行 ...
- day3 集合、文件操作、函数、局部变量
文章目录 1.集合 2.文件操作 3.函数 4.局部变量 1.集合 集合是一个无序的,不重复的数据组合,它的主要作用如下: 1)去重,把一个列表变成集合,就自动去重了 2)关系测试,测试两 ...
最新文章
- P3374 【模板】树状数组 1
- C指针原理(34)-Ncurses-文本终端的图形
- boost::mp11::mp_all相关用法的测试程序
- Spring Boot(二)应用实例
- C++ STL : 模拟实现STL中的string类
- linux 中阻塞与非阻塞 同步与异步
- vue mxgraph渲染xml页面_Vue的两个版本
- java url utf 8_java中文乱码解决之道(八)—–解决URL中文乱码问题
- TENSORFLOW 指定使用GPU跑
- Hadoop资源调度器
- IT项目经理每天每周都在干什么?附简要周报模板
- 21个以Bootstrap为框架的WordPress免费主题模板下载
- 图片标注工具LabelImg
- 使用SVD奇异值分解求解PCA+Python实现
- python命令行输入参数_Python命令行参数处理
- 利用flex弹性布局实现图片水平及垂直方向居中
- BERT in tweet_sentiment_extraction
- MC7812BTG详细参数介绍
- java程序设计答案电子工业出版社_java 语言程序设计(机械工业出版社)课后习题答案 - 下载 - 搜珍网...
- 虚幻4快速上手实战系列 之 三维弹球