python文件操作學習筆記
#文件操作:
讀:
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文件操作學習筆記