1. 程式人生 > >Python學習筆記系列——讀寫文件以及敏感詞過濾器的實現

Python學習筆記系列——讀寫文件以及敏感詞過濾器的實現

pict user tro users 創建 desktop enc 重建 文件

一、讀文件

#打開文件,傳入文件名和標識符,r代表讀
f= open(\\Users\ZC\Desktop\zc.txt,r)
#調用read方法一次性讀取文件的全部內容,存入內存,用str對象表示
print(f.read())
f.close()

#使用with無論程序是否對錯都會最後默認關閉文件。
with open(\\Users\ZC\Desktop\zc.txt,r) as f:
    print(f.read())

#使用read()會一次性讀取文件的所有內容,如果文件過大,內存會爆掉。可以反復調用read(size)方法,每次最多讀取size個字節的內容。
#調用readline()可以每次讀取一行內容,調用readlines()一次讀取所有內容並按行返回list。 f= open(\\Users\ZC\Desktop\zc.txt,r) for line in f.readlines(): print(line.strip()) #圖片、視頻等二進制文件,用rb模式打開 f= open(\\Users\ZC\Pictures\Camera Roll\8.jpg,rb) print(f.read()) #讀取非UTF-8編碼的文本文件,需要在open()函數中傳入encoding參數,errors參數表示遇到編碼錯誤如何處理。
f = open(\\Users\ZC\Desktop\gbk.txt, r, encoding=gbk,errors=ignore) print(f.read())

二、寫文件

  為了防止自己忘記寫close(),一般使用with語句,默認自動關閉文件。

#調用open()函數傳入標識符,w代表寫入(wb寫入二進制文件),如果文件不存在會自動創建。
f= open(\\Users\ZC\Desktop\zc.txt,w)
f.write(遇事不決,可問春風 \n)
f.close()
f=open(\\Users\ZC\Desktop\zc.txt
,r) print(f.read()) #w模式寫入文件,會直接覆蓋(即相當於刪除後重建),如果想追加,可使用a(append)模式。 f= open(\\Users\ZC\Desktop\zc.txt,a)

操作系統在寫入文件時,一般不會馬上寫到磁盤,而是放在內存中緩存,空閑時在寫入。調用close(),就是讓操作系統馬上寫入到磁盤中。

所以上面的代碼在寫入內容之後,在重新打開,才能調用read()查看文件的內容,否則會報錯。

關於open()函數標識符的幾個參數:

‘r‘:讀

‘w‘:寫

‘a‘:追加

‘r+‘ == r+w(可讀可寫,文件若不存在就報錯(IOError))

‘w+‘ == w+r(可讀可寫,文件若不存在就創建)

‘a+‘ == a+r(可追加可寫,文件若不存在就創建)

如果是對應的二進制文件,都加上一個b即可。

三、敏感詞過濾器

#創建文件,寫入內容
def text_create(name,msg):
    desktop_path = C://Users/ZC/Desktop/
    full_path = desktop_path + name + .txt
    file = open(full_path,w)
    file.write(msg)
    file.close()

#敏感詞為SB,替換成***
def text_filter(word,cencored_word = SB,changed_word = ***):
    return word.replace(cencored_word,changed_word)

#msg經過text_filter過濾之後存入到clean_msg,然後調用text_create寫入。
def text_censored_create(name,msg):
    clean_msg = text_filter(msg)
    text_create(name,clean_msg)
text_censored_create(test,你是個SB)

Python學習筆記系列——讀寫文件以及敏感詞過濾器的實現