python檔案操作學習筆記

2021-09-21 04:58:35 字數 1086 閱讀 1218

#檔案操作:

讀:f = open("/users/zhouhaijun/python/01.py","r")

x = f.read()

print x

寫:f = open("/users/zhouhaijun/python/file_01.py","wb")

f.write("ok")

f.close()

讀:f = open("/users/zhouhaijun/python/file_01","r")

text = f.read() #text = f.read(100)

print text

讀取一行:

print f.readline()  #按行讀取

接下來的函式是拷貝檔案,一次讀寫五十個字元。第乙個引數是源文 件名,第二個引數是新檔名 

def copyfile(oldfile, newfile):

f1 = open(oldfile,"r")

f2 = open(newfile,"w")

while 1:

text = f1.read(50)

if text == "":

break

f2.write(text)

f1.close()

f2.close()

return

接下來的例子是行處理程式,函式

filterfile

拷貝乙個檔案,同時將舊

檔案中不是以「#」開頭的行寫入新檔案中:

def fileterfile(old, new):

sfile = open(old, "r")

dfile = open(new, "w")

while 1:

text = sfile.readline()

if text =="":

break

elif:

text[0] = "#":

continue

else:

dfile.write(text)

sfile.close()

dfile.close()

Python學習筆記《檔案操作》

python的檔案操作容易上手,我選取了一些比較常用的。keep 開啟檔案 和c有點相像 f open friend.cpp 會讀取出來整個檔案的內容 小心記憶體不夠 f.read f.close with open friend.cpp as f f.read 逐行讀取 readlines 可以返...

python學習筆記 檔案操作

python檔案操作流程 開啟 讀寫 關閉 1.開啟檔案及開啟方式 file obj open filename mode filename 原字串 r d text.t 轉義字串 d text.t mode r w a b 唯讀r 可寫 w 此外還有a,b 2.讀寫 1.var file obj....

Python學習筆記 檔案操作

掌握點 列印螢幕 print方法,可以使用逗號 列印多個值 如 print 總數量 totallines讀取鍵盤輸入 1 raw input 提示資訊 從標準輸入讀取乙個行,並返回乙個字串 去掉結尾的換行符 str raw input 請輸入資訊 print str2 input 提示資訊 與raw...