2.6 使用for循环遍历文件
需要访问文件,那么首先需要打开文件
open ---内置函数
help(open)
打开(…)
打开(名称[,模式[,缓冲]])->文件对象
使用file()类型打开文件,返回文件对象。这是
打开文件的首选方法。看到文件。获取更多信息。
类型 | 说明 |
---|---|
r: | 以读的方式打开 |
w: | 以写的方式打开(文件不存在就会创建,文件存在将会进行覆盖) |
a: | 以追加的模式 |
r+: | 以读写模式打开 |
w+: | 以读写模式打开(参见w) |
a+: | 以读写模式打开(参见a) |
rb: | 以二进制读的模式打开(打开二进制文件的时候,就需要加上这个) |
wb: | 以二进制写的模式打开(参见b) |
ab: | 以二进制追加的模式打开(参见a) |
rb+: | 以二进制读写模式打开(参见r+) |
wb+: | 以二进制读写模式打开(参见w+) |
ab+: | 以二进制读写模式打开(参见a+) |
例:
In [2]: open('/tmp/1.txt')
Out[2]: <open file '/tmp/1.txt', mode 'r' at 0x7fb5c999ed20>
如果没有标明打开方式,将默认以 r 的方式进行打开 打开的时候,返回的是一个文件对象
需要拿一个变量进行接收
In [2]: open('/tmp/1.txt')
Out[2]: <open file '/tmp/1.txt', mode 'r' at 0x7fb5c999ed20>
In [3]: fd = open('/tmp/1.txt')
In [4]: fd //这个变量为文件描述符
Out[4]: <open file '/tmp/1.txt', mode 'r' at 0x7fb5c999ec90>
.close 关闭打开的文件
In [10]: fd
Out[10]: <closed file '/tmp/1.txt', mode 'r' at 0x7fb5c999ec90>
以w方式进行打开(将会截断文件这时,才从源文件中打开,将没有任何信息)
In [11]: fd = open('/tmp/1.txt','w')
In [12]: fd.write("a")
In [14]: fd.close() //这个操作,个人觉得理解为保存退出,会比较好,或者说是不再对文件进行操作
另外一个复制的ssh上,可以实时查看文件的变化
[root@iZwz9jd3zodsn1e1yy2nlkZ ~]# cat /tmp/1.txt
123,456,789
123,456,789
123,456,789
123,456,789
123,456,789
123,456,789
[root@iZwz9jd3zodsn1e1yy2nlkZ ~]# cat /tmp/1.txt
a[root@iZwz9jd3zodsn1e1yy2nlkZ ~]# //这里可以看到,源文件已经被改变
- a 方式进行打开
.write 写文件,只能以字符串的方式进行写
In [36]: fd.write(123)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-36-e571bc99ffd3> in <module>()
----> 1 fd.write(123)
TypeError: expected a character buffer object
In [37]: fd.write('aabbcc\n')
a123/n123/nabc/n[root@iZwz9jd3zodsn1e1yy2nlkZ ~]# cat /tmp/1.txt
a123/n123/nabc/naabbcc
In [15]: fd = open('/tmp/1.txt','a')
In [16]: fd.write('123/n')
In [17]: fd.write('123/n')
In [18]: fd.write('abc/n')
In [19]: fd.close()
a[root@iZwz9jd3zodsn1e1yy2nlkZ ~]# cat /tmp/1.txt
a123/n123/nabc/n[root@iZwz9jd3zodsn1e1yy2nlkZ ~]#
- .read 读取文件(返回的字符串)
In [20]: fd = open('/tmp/1.txt')
In [21]: fd.read()
Out[21]: 'a123/n123/nabc/n'
In [22]: fd.read()
Out[22]: '' //第二次读的时候,就没有信息了。
第二次读的时候,就没有信息了,因为,读取对象,是从头到尾进行读取,指针一旦读到文件的最后,那么将不能再读出任何信息
In [40]: fd.read(2) //读了两个指针位
Out[40]: 'a1'
In [41]: fd.read()
Out[41]: '23/n123/nabc/naabbcc\n' //因为指针位置移动了。将从之后的进行操作
- .readline()
读取一行(返回的是字符串)
In [43]: fd = open('/tmp/1.txt')
In [44]: fd.readline()
Out[44]: '123\n'
In [45]: fd.readline()
Out[45]: '456\n'
In [46]: fd.readline()
Out[46]: '789\n'
In [47]: fd.readline()
Out[47]: 'abc\n'
In [48]: fd.readline()
Out[48]: 'def\n'
In [49]: fd.readline()
Out[49]: ''
In [50]: fd = open('/tmp/1.txt')
In [51]: fd.readline(2) //如果加入数值,貌似和read效果一样
Out[51]: '12'
In [52]: fd.readline(5)
Out[52]: '3\n
- .readlines()
读取多行 将文件以列表形式返回
In [54]: fd = open('/tmp/1.txt')
In [55]: fd.readlines()
Out[55]: ['123\n', '456\n', '789\n', 'abc\n', 'def\n']
In [56]: fd = open('/tmp/1.txt')
In [57]: fd.readlines(2)
Out[57]: ['123\n', '456\n', '789\n', 'abc\n', 'def\n']
案例
循环读取文件
#!/user/bin/python
fd.open('/tmp/1.txt')
for line in fd.readlines():
print line, //因为文件里面默认就有一个换行,如果不加抑制换行,那读取的结果就是两个换行
[root@iZwz9jd3zodsn1e1yy2nlkZ ~]# !py
python 1.py
123
456
789
abc
def
[root@iZwz9jd3zodsn1e1yy2nlkZ ~]# !vi
vi 1.py
[root@iZwz9jd3zodsn1e1yy2nlkZ ~]# !pyt
python 1.py
123
456
789
abc
def
注:fd.readlines() 在程序里面加上这个的话,如果是特别大的文件,那么将会消耗很多的内存,以为,这个产生的是一个列表,因为fd 默认赋值到的时候是对象;
所以,可以这么来写
#!/user/bin/python
fd = open('/tmp/1.txt')
for line in fd:
print line
[root@iZwz9jd3zodsn1e1yy2nlkZ ~]# !pyt
python 1.py
123
456
789
abc
def
这样来循环,等同于使用了默认的一个.next()的方法
In [58]: fd = open('/tmp/1.txt')
In [59]: fd.next()
Out[59]: '123\n'
In [60]: fd.next()
Out[60]: '456\n'
In [61]: fd.next()
Out[61]: '789\n'
In [62]: fd.next()
Out[62]: 'abc\n'
In [63]: fd.next()
Out[63]: 'def\n'
In [64]: fd.next()
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-64-3df4eef70a28> in <module>()
----> 1 fd.next()
要养成一个好习惯,使用完对象以后,主动的进行fd.close,不然将会占用内存,虽然对象也会自动关闭,当这也需要一定的时间
2.7 使用while循环遍历文件
#!/usr/bin/python
with open('/tmp/1.txt') as fd:
while True:
line = fd.readline()
if not line:
break
print line,
[root@iZwz9jd3zodsn1e1yy2nlkZ ~]# python 2.py
123
456
789
abc
def
with open,因为with为语法,需要做换行符,这样可以免去手动关闭文件对象的命令,如果不那么做,这个脚本将会对内存有一定的占用
2.8 统计系统剩余的内存
案例,统计free 内存
因为命令也是对文件的信息,进行获取,所以free 取的就是/proc/meminfo
#!/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]
bareak //退出循环
print ('total = %s\nfree = %.2f' % (total,(int(free)/1024.0))+'M')
[root@iZwz9jd3zodsn1e1yy2nlkZ ~]# python 3.py
total = 3881688
free = 2043876
[root@iZwz9jd3zodsn1e1yy2nlkZ ~]# free
total used free shared buff/cache available
Mem: 3881688 130204 2045580 360 1705904 3476228
Swap: 0 0 0
%.2f 字符串格式化,定义为浮点数,并且有2位小数
In [73]: for i in range(3):
...: print type(i),i
...:
<type 'int'> 0
<type 'int'> 1
<type 'int'> 2
In [75]: for i in range(3):
...: a = '%f' %i
...: print type(a),i
...:
<type 'str'> 0
<type 'str'> 1
<type 'str'> 2
字符串方法 .startswith()
startswith(…)
.startswith(prefix[, start[, end]]) -> bool
如果S以指定的前缀开头,则返回True,否则返回False。
可选的开始,测试从那个位置开始。
对于可选的端,停止在那个位置比较S。
前缀也可以是尝试的字符串元组。
- .split 分割字符串
In [69]: b = '123 abc ABC'
In [70]: b.split()
Out[70]: ['123', 'abc', 'ABC']
In [71]: b.split()[1]
Out[71]: 'abc'
2.9 数据类型转换计算(计算mac地址)
类型转换
int()函数
十六进制字符串转为十进制
int('12',16)
18
int('0x12',12)
18
0x表示1十六进制的前缀
十进制转为十六进制
hex()
小练习
求mac地址的下一个地址
- 所谓的下一个mac地址,就是mac地址最后的一个位 + 1
- 首先知道一个mac地址
#!/usr/bin/evn python
macaddr = '00-FF-60-FA-B9-A3'
prefix_mac = macaddr[:-3]
last_two = macaddr[-2:]
plus_one = int(last_two, 16) +1
if plus_one in range(10):
new_last_two = hex(plus_one)[2:]
new_last_two = '0' + new_last_two
else:
new_last_two = hex(plus_one)[2:]
if len(new_last_two) ==1:
new_last_two = '0' + new_last_two
new_mac = prefix_mac + ':' + new_last_two
print new_mac.upper()
3.0 数据类型转换(列表与字典相互转换)
字符串转列表
list(string)
In [80]: list(s)
Out[80]: ['a', 'b', 'c']
In [81]: s = 'abc'
In [82]: list(s)
Out[82]: ['a', 'b', 'c']
列表转字符串
'',join(list)
In [88]: l
Out[88]: ['a', 'b', 'c']
In [89]: ''.join(l)
Out[89]: 'abc'
可以定义分隔符
In [90]: '.'.join(l)
Out[90]: 'a.b.c'
In [91]: ':'.join(l)
Out[91]: 'a:b:c'
字符串转元组
tuple(string)
In [92]: s
Out[92]: 'abc'
In [93]: t = tuple(s)
In [94]: t
Out[94]: ('a', 'b', 'c')
元组转字符串
''.join(tuple)
In [94]: t
Out[94]: ('a', 'b', 'c')
In [95]: ':'.join(t)
Out[95]: 'a:b:c'
字典转换为列表
In [100]: dic1
Out[100]: {'a': 1, 'b': 2}
In [101]: dic1.items()
Out[101]: [('a', 1), ('b', 2)]
列表转换为字典
in [105]: l1
Out[105]: [('a', 1), ('b', 2)]
In [106]: dict(l1)
Out[106]: {'a': 1, 'b': 2}