Python第五天 文件訪問 for循環訪問文件 while循環訪問文件 字符串的startswith函數和split函數
目錄
Python第二天 變量 運算符與表達式 input()與raw_input()區別 字符編碼
Python第三天 序列 數據類型 數值 字符串 列表 元組 字典
Python第四天 流程控制 ifelse條件判斷 forwhile循環
Python第五天 文件訪問 for循環訪問文件 while循環訪問文件 字符串的startswith函數和split函數
Python第七天 函數 函數參數 函數變量 函數返回值 多類型傳值 冗余參數 函數遞歸調用 匿名函數 內置函數 列表表達式/列表重寫
Python第八天 模塊 包 全局變量和內置變量__name__ Python path
Python第九天 面向對象 類定義 類的屬性 類的方法 內部類 垃圾回收機制 類的繼承
Python第十天 print >> f,和fd.write()的區別 stdout的buffer 標準輸入 標準輸出 標準錯誤 重定向
Python第十二天 收集主機信息 正則表達式 正則表達式 無名分組 有名分組
Python第十四天 序列化 pickle模塊 cPickle模塊 JSON模塊 API的兩種格式
Python文件訪問
open
r:以讀方式打開
w :以寫方式打開,如果文件已經有內容,會覆蓋
a :以追加模式
r+ :以讀寫模式打開
w+:以讀寫模式打開 (參見 w )
a+:以讀寫模式打開 (參見 a )
rb:以二進制讀模式打開
wb:以二進制寫模式打開 (參見 w )
ab:以二進制追加模式打開 (參見 a )
rb+:以二進制讀寫模式打開 (參見 r+ )
wb+:以二進制讀寫模式打開 (參見 w+ )
ab+: 以二進制讀寫模式打開 (參見 a+)
with open :python2.6才有的方法,python2.5沒有,用with open,退出with open代碼塊之后的代碼不需要顯式fd.close()
#!/usr/bin/python
with open('/proc/meminfo') as fd:
for line in fd:
if line.startswith('MemTotal'):
total = line.split()[1]
continue
if line.startswith('MemFree'):
free = line.split()[1]
break
print "%.2f" % (int(free)/1024.0)+'M'
文件的方法
fd.close():不執行fd.close(),python程序退出的時候也會close文件
fd.read()
fd.readline()
fd.readlines() :返回一個列表,每個元素都會加上一個換行符\n
next():一行一行讀取
for循環訪問文件
第一種 readlines全部把文件內容讀到內存
#!/usr/bin/python
fd = open('/tmp/tmp.txt')
for line in fd.readlines():
print line,
--------------------------
第二種 一行一行的讀到內存 比較節省內存
#!/usr/bin/python
fd = open('/tmp/tmp.txt')
for line in fd:
print line,
這里的fd是一個對象,有fd.next()方法,是顯示文件一行,那么for i in fd就相當于一直在執行fd.next()方法,直到文件結束
while循環訪問文件
#!/usr/bin/python
with open('/tmp/tmp.txt') as fd:
while True:
line = fd.readline()
if not line:
break
print line,
字符串的startswith函數和split函數
startswith()函數:匹配字符串中的行,完全匹配,不能模糊匹配
split()函數:切割字符串,默認以空格為分隔符
isdigit()函數:判斷字符串是否是數字
string.digits函數:返回數字0123456789
#!/usr/bin/env python import os import sys import string def isNum(s): for i in s: if i in string.digits: if i.isdigit(): continue else: return False return True if isNum(sys.argv[1]): print sys.argv[1]
In [5]: a.isdigit()
Out[5]: False
#!/usr/bin/python
with open('/proc/meminfo') as fd:
for line in fd:
if line.startswith('MemTotal'):
total = line.split()[1]
continue
if line.startswith('MemFree'):
free = line.split()[1]
break
print "%.2f" % (int(free)/1024.0)+'M'
文章列表
![]() |
不含病毒。www.avast.com |