python04篇 檔案操作(二)、集合
阿新 • • 發佈:2020-08-27
一、檔案操作(二)
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 # 如果是大檔案的話,如下處理 forline 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條件