建立一個檔案並往裡面寫入內容
import os# coding='utf-8'#取得OS的分行符號ls = os.linesep# 擷取檔案名稱while True: fname = raw_input('input file name: ') if os.path.exists(fname): print "ERROR : '%s' already exists!" % fname else: breakprint fname#擷取檔案的內容all = []print "\nEnter lines('.' by iteslf to quit).\n"#讀取使用者的輸入while True: entry = raw_input('> ') if entry == '.': break else: all.append(entry)#寫入檔案fobj = open(fname,'w')fobj.writelines(['%s%s' % (x, ls ) for x in all])fobj.close()print "DONE"
讀取檔案內容並顯示出來
# coding='utf-8'# 擷取檔案名稱fname = raw_input('input file name: ')print fnametry: fobj = open(fname,'r')except IOError, e: print "**** file open: ",eelse: for eachLine in fobj: print eachLine, fobj.close();
擷取數值的類型.注意python作為進階語言,卻沒有對數值進行統一,還是分屬於幾個類型:整型,浮點型,長整型,複數
# coding='utf-8'# 擷取數值的類型def getNumType(num): print num, 'is', #判定參數一是否為參數二當中的某個元素的執行個體 if isinstance(num, (int,long,float,complex)): print 'a number of type: ',type(num).__name__ else: print 'not a number at all' getNumType(-68)getNumType(99999999999999999999999999999L)getNumType(98.6)getNumType(-5.2+1.9j)getNumType("1212")