1. 程式人生 > 其它 >【Python】讀寫文字檔案

【Python】讀寫文字檔案

技術標籤:pythonpython

一、python讀取文字檔案

def ReadFile(filename,mode = 'r'):
    """
    讀取檔案內容
    @filename 檔名
    return string(bin) 若檔案不存在,則返回空字串
    """

    import os
    if not os.path.exists(filename):return""

    fp = open(filename,mode,encoding="utf-8")
    f_body = fp.read()
    fp.close()
    return f_body

#讀取文字檔案
txt = ReadFile("員工資訊.txt")
print(txt)

執行結果:

二、python寫入文字檔案

def WriteFile(filename,s_body,mode='w+'):
    """
    寫入檔案內容
    @filename 檔名
    @s_body 欲寫入的內容
    """

    fp = open(filename,mode)
    fp.write(s_body)
    fp.close()

#寫入文字檔案
WriteFile("1.txt","Hello World!")

執行結果: