本節主要介紹檔案相關的操作
寫乙個檔案
%
%writefile chen.txt
hello python
chen mo
how are you
writing chen.txt
讀取全部內容txt =
open
('./chen.txt'
)
allcontent = txt.read(
(allcontent)
讀取全部並放入陣列hello python
chen mo
how are you
lines = txt.readlines(
(lines)
for line in lines:
("current line:"
, line)
關閉當前檔案['hello python\n', 'chen mo\n', 'how are you\n']
current line: hello python
current line: chen mo
current line: how are you
覆蓋式寫檔案txt.close(
)
追加式寫檔案txt =
open
('mo.txt'
,'w'
)txt.write(
"hello mo"
)txt.write(
"\n"
)txt.write(
"how are you"
)txt.write(
"\n"
)txt.close(
)
with這種方式可以省略手動關閉檔案的操作,即不需要呼叫.close()txt =
open
('mo.txt'
,'a'
)txt.write(
"hello mo"
)txt.write(
"\n"
)txt.write(
"how are you"
)txt.write(
"\n"
)txt.close(
)
with
open
('mo.txt'
,'w'
)as f:
f.write(
"hello!"
)
Python學習筆記(十二)
1.語法錯誤和異常錯誤 while true print hello python error message file c programming eclipse project pythonstudy exception.py line 9 while true print hello pyth...
學習筆記 使用Python對檔案進行簡單操作
函式 shutil.rmtree path ignore errors onerror 該函式刪除乙個完整的目錄樹,path必須指向乙個目錄。如果ignore errors為true,移除失敗的error會被忽略。否則,該error將會被onerror處理。onerror funciton,path...
Python學習筆記(十二) Python模組
一 python模組 python 模組 module 是乙個 python 檔案,以 py 結尾,包含了 python 物件定義和python語句。模組讓你能夠有邏輯地組織你的 python 段,把相關的 分配到乙個模組裡能讓你的 更好用,更易懂。模組能定義函式,類和變數,模組裡也能包含可執行的 ...