Python學習筆記(四) 檔案讀取

2021-10-03 23:44:32 字數 1389 閱讀 6045

教程:莫煩python

環境:pycharm

· 寫開啟&寫入內容

text="this is a test.\nthe second line\nfinal line"

my_file=open('myfile.txt','a') #以寫形式開啟檔案

my_file.write(text) #往檔案裡寫內容

my_file.close() #關閉檔案

· 追加開啟&在檔案末尾加寫內容

text="\nthe addd line\nnewfinal line"

my_file=open('myfile.txt','a') # 以追加寫的形式開啟檔案 myfile.txt

· 讀開啟&讀出所有內容

· 讀開啟&讀檔案一行內容

#全部輸出

print(content)

my_file.close()

#迭代輸出

Python學習筆記 四 檔案操作

讀取鍵盤輸入 buf raw input please input your name buf raw input 開啟檔案 如果hello.txt不存在 fp open hello.txt w w是說建立這個檔案,以寫的方式開啟 fp.write text fp.close 如果hello.txt...

Python學習筆記之四 檔案讀寫

f open mhposition.txt r f.close 表示磁碟目錄 等於不寫表示當前目錄 表示上一級目錄 with open path to file r as f print f.read 這樣就不用寫close了!read 會一次性讀取檔案的全部內容 而readlines 一次讀取所有...

python學習 四 檔案處理

我們常用open來開啟檔案 open file,mode r buffering 1,encoding none,errors none,newline none,closefd true,opener none open file and return a stream.raise ioerror...