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