Python 語言 講義  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 A B C


檔案寫入與讀取


寫入 讀取
integer=128
float=24.54
lt1=[1,2,3,5,8]
str1="This is a book."
fileObject = open("C:\\Temp\\a.out","w")
#fileObject.write(integer) #錯的寫法
fileObject.write(str(integer)+'\n')

fileObject.write(str(float)+'\n')

fileObject.write(str(lt1)+'\n')

fileObject.write(str1+'\n')




fileObject.close()
 




fileObject = open("C:\\Temp\\a.out","r")

str1 = fileObject.readline()
integer=eval(str1)
str1 = fileObject.readline()
float=eval(str1)
str1 = fileObject.readline()
lt1=eval(str1)
str1 = fileObject.readline()
print(integer)
print(float)
print(lt1)
print(str1)
fileObject.close()
 

連續寫入與讀取

寫入 讀取
st0="望月有懷"
st1="清泉映疏鬆,不知幾千古。"
st2="寒月搖清波,流光入窗戶。"
st3="對此空長吟,思君意何深。"
st4="無因見安道,興盡愁人心。"
fileObject = open("C:\\Temp\\a.out","w")
fileObject.write(st0+'\n')
fileObject.write(st1+'\n')
fileObject.write(st2+'\n')
fileObject.write(st3+'\n')
fileObject.write(st4+'\n')
fileObject.close()
 





fileObject = open("C:\\Temp\\a.out","r")
for str1 in fileObject:
 print(str1,end='')
fileObject.close()
 

檢查檔案是否存在

import os.path
if os.path.isfile("C:\\Temp\\a.out"):
 print("File exist")
else:
 print("File not found")




Python 語言 講義  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 A B C