2.6 使用for循環遍歷文件
打開文件: 需要藉助內置函數open()
open(...)
open(name[, mode[, buffering]]) -> file object name:文件名 mode 打開方式(讀寫、二進制等)
Open a file using the file() type, returns a file object. This is the
preferred way to open a file. See file.__doc__ for further information.
以open()內置函數打開的文件返回的是一個文件對象
•open
r:以讀方式打開 只能讀,不能改寫,文件不存在會報錯
w :以寫方式打開 文件不存在會創建文件,小心操作,會更改文件內容
a :以追加模式 文件存在,在文件後追加,文件不存在則創建
主要使用 r,w,a三種
r+ :以讀寫模式打開
w+:以讀寫模式打開 (參見 w )
a+:以讀寫模式打開 (參見 a )
rb:以二進制讀模式打開
wb:以二進制寫模式打開 (參見 w )
ab:以二進制追加模式打開 (參見 a )
rb+:以二進制讀寫模式打開 (參見 r+ )
wb+:以二進制讀寫模式打開 (參見 w+ )
ab+: 以二進制讀寫模式打開 (參見 a+)
•with open
fd = open('/tmp/1.sh')
<open file '/tmp/1.sh', mode 'r' at 0x13f3c00> 返回的是一個在內存裏的文件對象
type(fd)
file fd是一個file類型
In [7]: fd. 文件對象的方法
fd.close fd.errors fd.isatty fd.newlines fd.readinto fd.seek fd.truncate fd.xreadlines
fd.closed fd.fileno fd.mode fd.next fd.readline fd.softspace fd.write
fd.encoding fd.flush fd.name fd.read fd.readlines fd.tell fd.writelines
close() 關閉文件
fd = open('/tmp/1.sh','w') 以w方式打開文件
fd.write("a") 對文件寫入 write方法只能寫入字符串,而且原文件內容會消失 write方法只接受字符串
write完成後必須使用 close()方法關閉文件,寫入纔會生效
fd.read() 把文件內容讀一遍,讀完之後指針找到文件的最後,再次read(),則讀取不到內容了,將返回一個空的字符串
read(2) 表示讀2個字符
fd.readline() 每次執行讀取一行
fd.readlines() 一次性讀取所有行,返回的是一個list列表
fd.readlines()
['123\n', '43\n', '5\n', '1\n'] 返回列表
使用for循環遍歷文件
#!/usr/bin/python
fd=open('/tmp/1.sh')
for line in fd.readlines():
print line,
問題,如果文件很大,則內存開銷會很大
優化寫法 for line in fd: 這樣的話他遍歷的是一個對象,而不是打開一個大的列表
fd.next() 方法
2.7 使用while循環遍歷文件
#!/usr/bin/python
fd=open('/tmp/1.sh')
while True:
line=fd.readline()
if not line: 如果讀到空行,if 空行就是flase not false就是true 然後執行break
break
print line,
使用with open 使用with open不用close文件(python2.6以後才支持)
with open('/tmp/1.sh') as fd:
while True:
line=fd.readline()
if not line:
break
print line,
2.8 統計系統剩餘的內存
統計系統中可用的內存
cat /proc/meminfo 內存使用在/proc/meminfo文件中,其中第一第二行
MemTotal: 999936 kB 總的內存
MemFree: 697388 kB 剩餘內存
腳本思路,通過對這個文件做一個遍歷,然後使用startswith()方法 查找以固定字符串開頭的行,然後使用split()方法切割行取出需要的值
#!/usr/bin/python
#coding:utf-8
with open('/proc/meminfo') as fd:
for line in fd:
if line.startswith('MemTotal'): 調用startswith方法,找到MemTotal開頭的行
total=line.split()[1] 切割這一行的字符串,取出total的值
continue 遍歷第一行的時候找到了 continue退出本次循環,優化程序
if line.startswith('MemFree'):
free=line.split()[1]
break 如果已經全部找到了,則退出for循環,優化程序
print "%.2fMB" % (int(free)/1024.0) 格式化輸出
2.9 數據類型轉換(計算mac地址)
python數據類型有:數值型 字符串型 列表 元組 字典 各個數據類型之間是可以轉換的\
一、十六進制字符串轉爲十進制
int(‘12' ,16)
18
int('0x12' ,16)
18
二、十進制轉爲十六進制
hex(10)
'0xa‘
注意:字符串之間是無法進行運算的,只有數字之間才能進行算術計算
十進制轉爲字符串
str(10)
'10'
字符串轉爲十進制
int('10')
例子:計算網卡mac地址的下一個地址 也就是00:0c:29:f5:20:7c 7c+1 比如服務器上有多個地址 mac地址基本都是連續着的
腳本實現
#!/usr/bin/python
macaddr = '00:0c:29:f5:20:7c'
prefix_mac=macaddr[:-3]
last_two = macaddr[-2:]
plus_one=int(last_two,16)+1
new_last_two=hex(plus_one)[2:]
new_mac=prefix_mac + ':' + new_last_two
print new_mac
3.0 數據類型轉換(列表與字典相互轉換)
•字符串轉列表
list(string)
•列表轉字符串
''.join(list) ''代表轉換成字符串後以什麼作爲分隔
•字符串轉元組
tuple(string)
•元組轉字符串
''.join(tuple)
元祖轉列表,列表轉元組
list(tuple) tuple(list)
•列表與元組互相轉換
•字典轉換成列表
字典的items()方法
•列表轉爲字典
- dict()