python笔记——python生物信息学数据管理-数据读写

#第二部分

#文件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循环逐行读取文件

...    length=float(line.strip()) #去掉空格和换行符,转换为浮点数

...    data.append(length) #添加到数据列表中,append()进行添加

...

>>> data

[16.38, 139.9, 441.46, 29.03, 40.93, 202.7, 142.3, 346.0, 300.0]

>>> n_items=len(data) #数据的数量

>>> n_items

9

>>> total=sum(data) #总和

>>> total

1658.6999999999998

>>> shortest=min(data) #最小值

>>> shortest

16.38

>>> longest=max(data) #最大值

>>> longest

441.46

>>> data.sort() #将数据按升序排序

>>> 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()

#结果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 #关闭文本文件

#readlines()函数读取文件中所有内容,按分隔符逐行存储,而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

#读取文件并删除分隔符,且不常见列表变量

for line in open(filename):

line=line.strip()

#写文件

output_file=open('count.txt','w')

output_file.write('number of neuron lengths:7\n') #需要以换行符结束,write()不能自动换行

output_file.close()


#将文本转换为数字

>>> number=float('100.12')+100.0 #字符串转换为浮点数

>>> number=int(100.34) #浮点数转换为整数

>>> number

100


#数字转换为文本

>>> text=str(number)

>>> text

'100'

#str()函数的数字是未格式化的,不能对其数字来填充给定的列数

#字符串格式化,在数值转换成字符串时使用百分号只是要分配给整数的位数

>>> 'Result:%3i'%(17) #%3i表示字符串应该包含格式化为三位的整数,整数实际值在结尾的括号中

'Result: 17'

>>> 'Result:%8.3f'%(17) #%x.yf浮点数字符串,x是总字符数(包括小数点),y是小数位数

'Result:  17.000'

>>> name='E.coli' #%s格式化字符串,可以右对齐如%10s,左对齐%-10s

>>> 'hello,%s'%(name)

'hello,E.coli'

你可能感兴趣的:(python笔记——python生物信息学数据管理-数据读写)