python04篇 文件操作(二)、集合
一、文件操作(二)
1.1 利用with来打开文件
# with open ,python 会自动关闭文件 with open('a.txt', encoding='utf-8') as f: # f 文件句柄 # 文件中没有空行,下面按行读是没问题,如果有空行就不能往下读 while True: line = f.readline().strip() if line: print(line) else: break # 如果是大文件的话,如下处理 for line in f: line = line.strip() if line: print(line)
1.2 两个文件进行操作
# 两个文件操作 # 1.r模式打开a文件,w模式打开b文件 # 2.读取到a文件所有内容 # 3.把替换new_str写入b文件 # 4.把a文件删除掉,把b文件更名为a文件 import os with open('word.txt', encoding='utf-8') as fr, open('words.txt', 'w') as fn: for line in fr: line = line.strip() if line: new_line = line.replace('a', 'A') fn.write(new_line+'\n') os.remove('word.txt') os.rename('words.txt', 'word.txt')
二、集合
# set 天生去重 l = [1, 2, 3, 2, 3, 4, 1, 5, 6] # 定义set set1 = {1, 2, 3, 2, 3, 4, 1} set2 = set() # 定义空集合set set3 = set(l) # 强制转为set集合 set3.add(1) # 新增元素 set3.remove(1) # 删除元素 set3.update(set2) # 把一个集合加入到另一个集合中 # 交集 print(set3.intersection(set1)) # 取交集 等同于 set3 & set1 print(set3 & set1) # 并集 print(set3.union(set1)) print(set3 | set1) # 差集 print(set3.difference(set1)) # 在一个集合中存在,在另一个集合中不存在。此语句中就是set3中存在,set1中不存在的 print(set3 - set1) # 对称差集 print(set3.symmetric_difference(set1)) # 去掉两个集合交集之外的部分 print(set3 ^ set1) # 集合也可以循环 for s in set3: print(s)
三、三元表达式、列表生成式
3.1 三元表达式
# 三元表达式 age = 18 # 原写法 if age < 18: v = '未成年人' else: v = '成年人' # 三元表达式 写法 只能是if else可以用, 不能 v = '未成年人' if age < 18 else '成年人'
3.2 列表生成式
# 列表生成式 a = [1, 2, 3, 4, 5] c = [str(i) for i in a] d = [str(i) for i in a if i % 2 != 0] # 可以加上if条件
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· winform 绘制太阳,地球,月球 运作规律
· 上周热点回顾(3.3-3.9)