1. 程式人生 > >2018-11-23學習筆記

2018-11-23學習筆記

2.6 使用for迴圈遍歷檔案

開啟檔案:

open方式:

r:以只讀方式開啟,檔案不存在會報錯

w:以寫方式開啟,檔案不存在會建立,檔案存在會被覆蓋

a:以追加模式開啟,檔案存在會在檔案最後追加,檔案不存在會建立

r+:以讀寫模式開啟

w+:以讀寫模式開啟(參見w)

a+:以讀寫模式開啟(參見a)

rb:以二進位制寫模式開啟

wb:以二進位制寫模式開啟(參見w)

ab:以二進位制追加模式開啟(參見a)

rb+:以二進位制讀寫模式開啟(參見r+)

wb+:以二進位制讀寫模式開啟(參見w+)

ab+:以二進位制讀寫模式開啟(參見a+)

 

1. 預設以r方式開啟

 

2. 以其他方式開啟

 

3. fd = open('/root/file') 用內建函式open開啟檔案

fd.close() 使用open內建函式開啟後,使用fd.close()關閉;

讀取內容時指標會指向相應的位置,讀完顯示空字串;

 

fd.read() 讀取全部內容,從頭到尾;返回的是字串;

fd.read(2) 讀取兩位;

fd.readline() 每執行一次讀取一行;指標到最後返回空字串;

fd.readlines() 以列表形式讀取

fd.next() 執行一次顯示一行

 

4. fd = open('/root/file', 'w') 以w方式開啟檔案

只接受字串,不支援數值;

檔案內容會被覆蓋;

寫入完成後執行fd.close();

5. fd = open('/root/file', 'a') 以a方式開啟檔案

6. 指令碼示例:

#!/usr/bin/python

fd = open('/root/file')

for line in fd.readlines():

print line,

注:檔案裡本身有換行符,line後面加上逗號抑制print的換行符,不然會出現空行;

當檔案很大時fd.readlines會佔用很大記憶體,所以建議使用下面指令碼:

 

#!/usr/bin/python

fd = open('/root/file')

for line in fd:

print line,

注:for line in fd: 中fd是物件,迴圈時是遍歷一遍取一次資料,不佔用記憶體;


2.7 使用while迴圈遍歷檔案

1. while迴圈使用open遍歷檔案

#!/usr/bin/python

 

fd = open('/root/file')

while True:

x = fd.readline()

if not x:

break

print x,

fd.close()

注:迴圈遍歷檔案時結束時儘量fd.close()關閉檔案;

 

2. while 中使用with open遍歷檔案

不需要close了;

格式:with open() as xxx:

 

#! /usr/bin/python

with open('/root/file') as fd:

while 1:

line = fd.readline()

if not line:

break

print line,


2.8 統計系統剩餘的記憶體

1. 檢視系統剩餘記憶體

free 命令

cat /proc/meminfo

 

2. 字串的startswith()方法:

判斷是否有以指定字串開頭的行;

返回的是bool值,true或false;

 

3. 字串的split()方法:

以空格或則tab鍵分割,並在輸出為列表;

4. 統計系統剩餘記憶體,以及使用百分比:

#! /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

persent = '%.2f' % ((float(free)/float(total))*100)+'%'

print 'free:'+ '%.2f' % (int(free)/1024.0)+'M'

print 'free%:'+ persent

注:

float()轉換成浮點型

‘%.2f是字串格式化並保留小數點後兩位


2.9 資料型別轉換計算(計算mac地址)

1. 十六進位制字串轉為十進位制

  • int('12' ,16)
  • int('0x12' , 16)
  • 0x表示16進位制

 

2. 十進位制轉成十六進位制

hex(10)

3. 十進位制轉換字串

4. 字串轉成數字

5. python計算一個mac地址的下個地址

通常伺服器裡有多個網絡卡的話,網絡卡的mac地址基本都是挨著的。

#! /usr/bin/env

mac = '52:54:00:0c:9f:0a'

last_two = mac[-2:]

front_mac = mac[:-2]

plus_one = int(last_two ,16) + 1

if plus_one in range(10):

new_last_two = '0' + hex(plus_one)[2:]

elif len(hex(plus_one)[2:]) == 1:

new_last_two = '0' + hex(plus_one)[2:]

 

next_mac = front_mac + new_last_two

print next_mac


3.0 資料型別轉換(列表與字典相互轉換)

1. 字串轉列表

list[string]

2. 列表轉字串

‘’.join(list)

3. 字串轉元組

tuple(string)

4. 元組轉字串

''.join(tuple)

‘s’.join(): s 表示用什麼分割字串

5. 列表與元組互相轉換

6. 字典轉換成列表

字典的items()方法

7. 列表轉為字典

dict()