1内置函数 (BIF)
python中有很多内置函数,再遇到一个需求时候,优先考虑内置函数。内置函数使用的时候不需要导入命名空间
range():生成一个从0到某个数的数字列表
2从文件读取数据
2.1文件输出
python中的基本机制是基于行的,程序从文本文件读入数据,一次取到一个数据行
the_file = open('file.txt') # do something with data the_file.close()
@H_301_14@打开一个新的IDLE回话,切换目录到数据文件的目录
import os os.getcwd()//查看当前路径 os.chdir('/data/yitingfan/')
@H_301_14@data = open('sketch.txt') for each_line in data: print each_line
@H_301_14@data.close()
@H_301_14@两个处理字符串的方法
str.split('x'[,n])//第一个参数是分隔符,默认情况下尽可能多分解。第二个可选参数是分割的字段数目。 str.find('')//如果找到字符串,返回索引,如果没有找到,返回-1
@H_301_14@2.2处理异常
try:
@H_301_14@except:
3数据保存到文件
3.1向文件中写入
out=open("file.txt","w")//以写模式打开文件对象 python 3:print('write some data into file',file=out) python 2.x print >> out,"write data into file" //把数据写至一个文件对象 out.close()//关闭文件对象
@H_301_14@3.2处理异常
try: pass except IOError: print 'file error' finally: file.close()
@H_301_14@