2.6 使用for循環遍歷文件 2.7 使用while循環遍歷文件 2.8 統計系統剩餘的內存 2.9 數據類型轉換計算(計算mac地址) 3.0 數據類型轉換(列表與字典相互轉換)

2.6 使用for循環遍歷文件

open r:以只讀方式打開 w: 以寫方式打開 a: 以追加模式打開 r+: 以讀寫模式打開 w+: 以讀寫模式打開(參見w) a+: 以讀寫模式打開(參見a) rb: 以二進制模式打開python

read

咱們先寫一個文件,叫1.txt 內容以下 111 222 ccc ddd指針

打開文件code

fd = open('1.txt','r')
print (fd.read()),
print (fd.read()),  \\注意,咱們打印了兩次fd.read(),單隻輸出了一次,這是由於第一次read結束後指針已經移到了文件末尾,第二次read並不能取到值,相似的,readline和readlines也不能取到值

--------------
111
222
ccc
ddd

readline&readlines

fd = open('1.txt','r')
print (fd.readline())
-------
111

fd = open('1.txt','r')
print (fd.readlines())
--------------
['111\n', '222\n', 'ccc\n', 'ddd']

df.readlines 會返回一個列表,因此他是能夠遍歷的,但實際寫代碼時不建議你們這樣寫,由於當文件很大時readlines返回的列表會佔用大量內存資源,建議你們直接遍歷open返回的fb對象對象

fd = open('1.txt','r')
for line in fd:
	print (line),

注意使用open()的時候要記得關閉文件內存

fd = open('1.txt','r')
fd.close()

平時建議你們使用 with open ,它的使用方法和open相似,但會自動關閉文件,不須要手動close。資源

with open('1.txt','r') as fd:
	for line in fd:
		print line,

2.7 使用while循環遍歷文件

經過文件結束後的空字符串來判斷字符串

fd = open('1.txt','r')
while 1 :
	line = fd.readline()
		if not line:
		break
	print line,
fd.close()

2.8 統計系統剩餘的內存

咱們知道free命令實際查看的是 /proc/meminfo 這個文件,因此能夠經過python對這個文件進行遍從來獲取內存信息it

str.startswith()

s.startswith(prefix[,start[,end]]) ->boolio

判斷是否以指定字符串開頭,如果則返回Truefor循環

with open('/proc/meminfo','r') as f :
	for line in f:
		if line.startswith('MemTotal') :
			total = line.split()[1]   \\將字符串分割(默認以空格或tab分割),返回列表
			continue
		if line.startswith('MemFree') :
			free = line.split()[1]
print totle,free

2.9 數據類型轉換計算(計算mac地址)

十六進制、十進制互相轉換

十六進制轉換爲十進制

int('12',16)
----------
18

int('0x12',16)
----------
18

十進制轉換爲十六進制

hex(10)
----------
0x12

mac地址加一併輸出

mac = 'ee:35:a1:34:3b:01'

i = mac.split(':')[-1]
n = int (i,16)
n += 1
hexn = hex(n)
if n < 16 :
		end = '0' + str(hexn)[-1]
else :
		end = str(hexn)[-2:]

new_mac = mac[:-2] + end
print (new_mac.upper())

3.0 數據類型轉換(列表與字典相互轉換)

列表轉換成字符串

s.join()方法

s.join(iterable)  \\iterable是可迭代對象,s是分割可迭代對象的分割字符,能夠是「.」、「:」等字符串,當其爲空時就能夠合併可迭代對象

l1 = ["a","b","c"]
s1 = ""
s1.jion(l)
----------
abc

t = ("a","b","c")
s1 = ""
s1.join(t)
----------
abc

dictionary轉化成list

dic = {'a':1,'b',:2}
l = dic.items()
print (l)
----------
[('a', 1), ('b', 2)]   \\這種形式的列表可直接使用dict(l)來將列表轉化成字典
相關文章
相關標籤/搜索