python學習筆記[headfirst]

1內置函數 (BIF)

python中有不少內置函數,再遇到一個需求時候,優先考慮內置函數。內置函數使用的時候不須要導入命名空間
range():生成一個從0到某個數的數字列表python

2從文件讀取數據

2.1文件輸出

python中的基本機制是基於行的,程序從文本文件讀入數據,一次取到一個數據行函數

the_file = open('file.txt')
# do something with data
the_file.close()

打開一個新的IDLE回話,切換目錄到數據文件的目錄code

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

2.2處理異常

try:

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()//關閉文件對象

3.2處理異常

try:
    pass
except IOError:
    print 'file error'
finally:
    file.close()
相關文章
相關標籤/搜索