2014年9月2日 星期二

Python 讀檔寫檔

Python讀檔與寫檔

使用open這function並給參數'r'或'w'

'r' -> 讀檔 readline()
'w' -> 寫檔 write()

以下為簡單的範例

fin = open('test.txt', 'r')
fout = open('E:/python/fileTest/fileTest.txt', 'w')
while True :
 i = fin.readline()
 fout.write(i)
 if i=='': break
 print(i,end='')
fin.close()
fout.close()



with讀檔

當使用with此函數,程式在離開with區塊後會自行關檔

with open("test.txt") as f:
 for line in f:
  print(line)

沒有留言:

張貼留言