七、python打开文件方式
open
r: 读的方式
w:已写的方式打开
a:以追加的方式
r+ 读写模式
w+ 读写
a+ 读写
rb:二进制读模式打开
wb:以二进制写模式打开
ab 二进制追加模式
rb+ 二进制读写
wb+二进制读写
ab+二进制读写
with open
fd= open('/usr/local/python/1.txt','w') 打开文件
fd.close 关闭函数
fd.write("a") 写入字符串
fd.read() 读文件,默认从头到结尾,加数值表示读到第几位
fd.readline() 读一行 返回字符串
fd.readlines() 读多行 返回列表
for遍历文件 #!/usr/bin/python fd = open('/usr/local/python/1.txt') for i in fd: fd.readlines()(占用内存资源) print i, fd.close()
while遍历文件 #!/usr/bin/python fd = open('/usr/local/python/1.txt') while True: i = fd.readline() if not i: break print i, fd.close() ~ #!/usr/bin/python with open('/usr/local/python/1.txt') as fd: 自动关闭文件 while True: i = fd.readline() if not i: break print i,
例子 统计使用内存 #!/usr/bin/python with open('/proc/meminfo') as fd: # 查看内存的文件 /proc/meminfo for line in fd: if line.startswith('MemTotal'): # line.startswith(‘a’) 匹配以a开头的行 total = line.split()[1] # line.split()[1] 以空格为分隔符,形式列表,去第二段 continue if line.startswith('MemFree'): free = line.split()[1] break print "%.2f" % (int(free)/1024.0)+'M' #"%.2f" 格式化字符串 print "%.2f" % (int(total)/1024.0)+'M' c = float(free) / float(total)*100 print "%.2f" % c+'%' print "%.2f" % (float(free)/float(total)*100)+'%'
不要让以后的自己被嫌弃