1. 程式人生 > >【python初識】檔案儲存與異常

【python初識】檔案儲存與異常

檔案儲存與異常

1、開啟關閉檔案

import os
if os.path.exists('sketch.txt'):
  the_file = open('sketch.txt')
  print(the_file.readline(),end=' '
  the_file.close()
else:
  print('the data is missing')

2、split函式

for each_line in data:
  if not each_line.find(':') == -1
    (role,line_spoken) = each_line.split
(':',1) #分成兩部分

3、異常處理

try:
  the_file = open('sketch.txt')
  print(the_file.readline(),end=' '
except IOError:
  print('the data is missing')
finally:
   the_file.close()

try:
  with open ('it.txt',"w") as data:
  print("aag",file = data)
except IOError as err:
  print("File error:" + str(err) )

4、strip函式

(role,line_spoken) = each_line.split(':',1)
line_spoken = line_spoken.srep() #從字串去除不想要的字元

5、寫入檔案

out = open("data.out",'w')
print("NOR iii",file = out)
out.close()

6、儲存檔案

import pickle 

with open('mydata.pickle','wb') as msd
  pickle.dump([1,2,'t'],msd)

with open('mydata.pickle'
,'rb') as mrd mlist = pickle.load(mrd) print(mlist)