#第二部分
#文件neuron_data.txt
16.38
139.90
441.46
29.03
40.93
202.70
142.30
346.00
300.00
>>> data=[]
>>> for line in open('neuron_data.txt'): #for循環(huán)逐行讀取文件
...? ? length=float(line.strip()) #去掉空格和換行符,轉(zhuǎn)換為浮點數(shù)
...? ? data.append(length) #添加到數(shù)據(jù)列表中,append()進(jìn)行添加
...
>>> data
[16.38, 139.9, 441.46, 29.03, 40.93, 202.7, 142.3, 346.0, 300.0]
>>> n_items=len(data) #數(shù)據(jù)的數(shù)量
>>> n_items
9
>>> total=sum(data) #總和
>>> total
1658.6999999999998
>>> shortest=min(data) #最小值
>>> shortest
16.38
>>> longest=max(data) #最大值
>>> longest
441.46
>>> data.sort() #將數(shù)據(jù)按升序排序
>>> data
[16.38, 29.03, 40.93, 139.9, 142.3, 202.7, 300.0, 346.0, 441.46]
>>> output=open("results.txt","w") #以可寫模式打開新文件
>>> output.write("number of dendritic lengths: %4i \n"%(n_items)) #寫入文件
>>> output.write("total dendritic length? ? : %6.1f \n"%(total))
>>> output.write("shortest dendritic length? : %7.2f \n"%(shortest))
>>> output.write("longest dendritic length? : %7.2f \n"%(longest))
>>> output.write("%37.2f\n%37.2f"%(data[-2],data[-3]))
>>> output.close()
#結(jié)果results.txt
number of dendritic lengths:? ? 9
total dendritic length? ? : 1658.7
shortest dendritic length? :? 16.38
longest dendritic length? :? 441.46
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 346.00
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 300.00
#讀取文件
>>> text_file=open('neuron_data.txt') #打開一個文本文件
>>> lines=text_file.readlines() #讀取
>>> lines
['16.38\n', '139.90\n', '441.46\n', '29.03\n', '40.93\n', '202.70\n', '142.30\n', '346.00\n', '300.00\n']
>>> print lines
['16.38\n', '139.90\n', '441.46\n', '29.03\n', '40.93\n', '202.70\n', '142.30\n', '346.00\n', '300.00\n']
>>> text_file.close #關(guān)閉文本文件
<built-in method close of file object at 0x7f79d7bb7930>
#readlines()函數(shù)讀取文件中所有內(nèi)容,按分隔符逐行存儲,而read()讀取整個文件作為單個的字符串
>>> text_file=open('neuron_data.txt')
>>> lines=text_file.read()
>>> lines
'16.38\n139.90\n441.46\n29.03\n40.93\n202.70\n142.30\n346.00\n300.00\n'
>>> text_file.close
<built-in method close of file object at 0x7f79d7bb79c0>
#讀取文件并刪除分隔符,且不常見列表變量
for line in open(filename):
line=line.strip()
#寫文件
output_file=open('count.txt','w')
output_file.write('number of neuron lengths:7\n') #需要以換行符結(jié)束,write()不能自動換行
output_file.close()
#將文本轉(zhuǎn)換為數(shù)字
>>> number=float('100.12')+100.0 #字符串轉(zhuǎn)換為浮點數(shù)
>>> number=int(100.34) #浮點數(shù)轉(zhuǎn)換為整數(shù)
>>> number
100
#數(shù)字轉(zhuǎn)換為文本
>>> text=str(number)
>>> text
'100'
#str()函數(shù)的數(shù)字是未格式化的,不能對其數(shù)字來填充給定的列數(shù)
#字符串格式化,在數(shù)值轉(zhuǎn)換成字符串時使用百分號只是要分配給整數(shù)的位數(shù)
>>> 'Result:%3i'%(17) #%3i表示字符串應(yīng)該包含格式化為三位的整數(shù),整數(shù)實際值在結(jié)尾的括號中
'Result: 17'
>>> 'Result:%8.3f'%(17) #%x.yf浮點數(shù)字符串,x是總字符數(shù)(包括小數(shù)點),y是小數(shù)位數(shù)
'Result:? 17.000'
>>> name='E.coli' #%s格式化字符串,可以右對齊如%10s,左對齊%-10s
>>> 'hello,%s'%(name)
'hello,E.coli'