1. 程式人生 > >pythoncook 檔案和io

pythoncook 檔案和io

1、檔案不存在,則寫入;檔案存在則,報錯

try:

  with open('file','x') as f:

    f.write()

except FileExistsError:

  print('file exists')

相當於:if not os.path.exists('file'):

    with open('file','w') as f :

       f.write('')

  else:

    print('file exists')