文件操作是數據處理中的基礎操作,包括讀取、寫入、存儲/關閉等
#文件不存在時自動創建
a=open('D:/1python學習/重新學習python/file.txt','w')
b='hello,python'
a.write(b)
a.write('\nhi,girl')
a.close()
#文件存在時
a=open('D:/1python/file2.txt','r')
b=a.read()
print(b)
line1=a.readline() #讀取第一行
print(line1)
while True:
line=a.readline()
if len(line)==0:
break
print(line)
a.close()
操作過程中出現異常會終止程序運行,有個異常處理之後,我們可以讀取異常並繼續運行程序
#異常處理
print('python')
prints('python')
try:
print('python')
prints('python')
except Exception as error: #捕捉異常並存儲爲error
print(error)
————來自韋瑋老師課堂筆記