python讀取文字並將指定內容逐行寫入txt檔案儲存
阿新 • • 發佈:2020-12-25
文字檔案示例如下:
需求:篩選所有後綴是“ing”的詞,並將其儲存到新的txt檔案中。
程式碼如下:
# coding:utf-8
import os
ingword = []
for line in open("file.txt"): # 逐行讀取
for word in line.split():
if word.endswith("ing"): # 篩選後綴是“ing”的詞
ingword.append(word) # 字尾是“ing”的詞儲存到列表中
# 寫之前,先檢驗檔案是否存在,存在就刪掉
if os.path.exists("dest.txt"):
os.remove("dest.txt")
# 以寫的方式開啟檔案,如果檔案不存在,就會自動建立
file_write_obj = open("dest.txt", 'w') # 新檔案
for var in ingword:
file_write_obj.write(var) # 逐行寫入
file_write_obj.write('\n')
file_write_obj.close()
print ("儲存檔案成功")
完成如下: