python文件操作
open
r:以读方式打开
w:以写方式打开
a:以追加模式
r+:读写模式
w+:读写模式(参见w)
a+:读写模式(参见a)
rb:以二进制读模式打开
wb:以二进制写模式打开(参见w)
ab:以二进制追加模式打开(参见a)
rb+:以二进制读写模式打开(参见r+)
wb+:以二进制读写模式打开(参见w+)
ab+:以二进制读写模式打开(参见a+)
with open
In [34]: type(fd.read()) fd.read()是字符串类型Out[34]: strIn [30]: cat /tmp/tmp.txtaa456In [31]: fd=open('/tmp/tmp.txt') In [32]: fd.read(2) 读2个字符Out[32]: 'aa' In [33]: fd.read() 没有数字,代表从当前位置读到结尾Out[33]: '456'
使用for循环遍历文件
打开文件
[root@localhost ~]# vim forread.py#!/usr/bin/pythonfd=open('/tmp/tmp.txt')for line in fd: #或者使用for line in fd.readlines(): readlines()创建的按行的列表,文件如果是1G,占用内存大 print line, #使用,[root@localhost ~]# python forread.py daviddavid1david2david3
使用while循环遍历文件
打开文件
[root@localhost ~]# vim whileread.py #!/usr/bin/pythonfd = open('/tmp/tmp.txt')while True: line = fd.readline() if not line: break print line,fd.close()[root@localhost ~]# python whileread.py daviddavid1david2david3#使用with open(/bath/file) as fd,会自动调用fd.close(),with open下面的代码需要关键字,属于循环内容[root@localhost ~]# vim whileread.py #!/usr/bin/pythonwith open('/tmp/tmp.txt') as fd: while True: line = fd.readline() if not line: break print line,[root@localhost ~]# python whileread.py daviddavid1david2david3
打印mem total和mem free,使用startswith(a)判断字符串开头字母为a,返回true,否则返回false,split()分割字符串
[root@localhost ~]# cat /proc/meminfo MemTotal: 502092 kBMemFree: 10656 kBBuffers: 131744 kBCached: 236908 kBSwapCached: 64 kB[root@localhost ~]# vim memory.py#!/usr/bin/pythonwith open ('/proc/meminfo') as fd: for line in fd: if line.startswith('MemTotal'): total=line.split()[1] if line.startswith('MemFree'): free=line.split()[1]print total,free[root@localhost ~]# python memory.py502092 9156