文件I/O

打开文件
  open(name[,mode[,buffer]])
 文件模式
  r:读模式
  w:写模式
  a:追加模式
  b:二进制模式
  +:读/写模式
 Write()方法可将任何字符串写入一个打开的文件
 read()方法从一个打开的文件中读取一个字符串
 close()方法关闭文件
 对文件内容进行迭代
  1)按字节
   read()方法从一个打开的文件中读取一个字符串
   f = open(filename)
   char = f.read(1)
   while char:
    process(char)
    char = f.read(1)
   f.close()
  2)按行操作
   f = file(filename)
   while True:
    line = f.readline()
    if not line:break
    process(line)
   f.close()
  3)读取所有内容
   1)用read迭代每个字符
   f = file(filename)
   for char in f.read():
    process(char)
   f.close()
   2)用readlines迭代行
   f = open(filename)
   for line in f.readlines():
    process(line)
   f.close()
  4)使用fileinput实现懒惰行迭代【大文件时,readlines会占用太多内存】
   import fileinput
   for line in fileinput.input(filename):
    process(line)

原文地址:https://www.cnblogs.com/lens/p/4611246.html