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+'
')
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条件
原文地址:https://www.cnblogs.com/lhy-qingqiu/p/13574222.html