一、文件的读取操作
with open('test') as file_object:contents = file_object.read()print(contents)
# 用rstrip来消除每行结尾的换行符的影响with open('test') as file_object:for line in file_object:print(line.rstrip())
with open('test') as file_object:lines = file_object.readlines()for line in lines:print(line.rstrip())
二、写入文件
- r 读取模式
- w 写入模式
- a 附加模式
- r+ 读取和写文件模式
注意:如果你要写入的文件不存在,函数open()将自动创建它,然而,以写入(w)模式打开文件时千万要小心,因为如果指定的文件已经存在,Python将在返回文件对象前清空该文件
filename = 'program.txt'with open(filename,'w') as file_object:file_object.write("I love you!")
filename = 'program.txt'with open(filename,'a') as file_object:file_object.write("I not love you!")
