一、文件的读取操作

  1. with open('test') as file_object:
  2. contents = file_object.read()
  3. print(contents)
  1. # 用rstrip来消除每行结尾的换行符的影响
  2. with open('test') as file_object:
  3. for line in file_object:
  4. print(line.rstrip())
  1. with open('test') as file_object:
  2. lines = file_object.readlines()
  3. for line in lines:
  4. print(line.rstrip())

二、写入文件

  • r 读取模式
  • w 写入模式
  • a 附加模式
  • r+ 读取和写文件模式

注意:如果你要写入的文件不存在,函数open()将自动创建它,然而,以写入(w)模式打开文件时千万要小心,因为如果指定的文件已经存在,Python将在返回文件对象前清空该文件

  1. filename = 'program.txt'
  2. with open(filename,'w') as file_object:
  3. file_object.write("I love you!")
  1. filename = 'program.txt'
  2. with open(filename,'a') as file_object:
  3. file_object.write("I not love you!")

三、文件的光标定位