2.6 使用for循环遍历文件
open r:以只读方式打开 w: 以写方式打开 a: 以追加模式打开 r+: 以读写模式打开 w+: 以读写模式打开(参见w) a+: 以读写模式打开(参见a) rb: 以二进制模式打开
read
我们先写一个文件,叫1.txt 内容如下 111 222 ccc ddd
打开文件
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对这个文件进行遍历来获取内存信息
str.startswith()
s.startswith(prefix[,start[,end]]) ->bool
判断是否以指定字符串开头,若是则返回True
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)来将列表转化成字典