本人是java后端開發(fā)人員,這幾天在自學python,踩過一些坑,希望給大家一些幫助.
Python是有格式要求的!!!Python是有格式要求的!!!Python是有格式要求的!!!
縮進要合理,自己再寫一個python輸出文件的時候發(fā)現的,我把代碼提供出來
dbfilename = 'people-file'
ENDDB='enddb.'
ENDREC='endrec.'
RECSEP='=>'
def storeDbase(db):
dbfile = open(dbfilename,'w')
for key in db:
dbfile.write (key)
for(name,value) in db[key].items():
dbfile.write(name + RECSEP + repr(value) + '\n')
dbfile.write (ENDREC)
dbfile.write(ENDDB)
dbfile.close()
def loadDbase(dbfilename = dbfilename):
dbfile = open(dbfilename)
import sys
sys.stdin = dbfile
db = {}
key = input()
while key != ENDDB:
rec = {}
filed = input()
while filed != ENDREC:
name,value = filed.split(RECSEP)
rec[name] = eval(value)
filed = input()
db[key] =rec
key = input()
return db
if __name__ == '__main__':
from initdata import db
storeDbase(db)
這個是initdata.py
bob = {'name':'bob','age':20,'pay':1000}
sus = {'name':'sus','age':30,'pay':2000}
dac = {'name':'dac','age':50,'pay':3000}
sfc = {'name':'sfc','age':40,'pay':4000}
db = {}
db['bob'] = bob
db['sus'] = sus
db['dac'] = dac
db['sfc'] = sfc
當時我寫這個這段代碼的時候,寫成了這樣子
dbfilename = 'people-file'
ENDDB='enddb.'
ENDREC='endrec.'
RECSEP='=>'
def storeDbase(db):
dbfile = open(dbfilename,'w')
for key in db:
dbfile.write (key)
for(name,value) in db[key].items():
dbfile.write(name + RECSEP + repr(value) + '\n')
dbfile.write (ENDREC)
dbfile.write(ENDDB)
dbfile.close()
def loadDbase(dbfilename = dbfilename):
dbfile = open(dbfilename)
import sys
sys.stdin = dbfile
db = {}
key = input()
while key != ENDDB:
rec = {}
filed = input()
while filed != ENDREC:
name,value = filed.split(RECSEP)
rec[name] = eval(value)
filed = input()
db[key] =rec
key = input()
return db
if __name__ == '__main__':
from initdata import db
storeDbase(db)
細心的人已經發(fā)現了, 下面這段話的格式縮進有問題,但是在java里面只是格式不好看,并不影響編譯運行,而在python里卻影響,他會不執(zhí)行的,因為Python是有嚴禁的邏輯關系的:
Python第二章——行與縮進
if __name__ == '__main__':
from initdata import db
storeDbase(db)
就是這樣,(>ω<)喵!!!