#coding:gbk#10.2.1写入空文件#write_message.oy
filename ='programming.txt'withopen(filename,'w')as file_object:
file_object.write("I love programming.")withopen(filename)as file_object:
content = file_object.read()print(content)#调用open()时提供了两个实参,第一个实参是要打开的文件名,第二个实参('w')告诉Python要以写入模式打开这个文件#打开文件时,可指定读取模式('r')、写入模式('w')、附加模式('a')或让你能够读取和写入(文件的模式('r+')。#如果省略了模式实参,Python将以默认的只读模式打开文件。#如果要写入的文件不存在,函数open()将自动创建它。#然而,以写入('w')模式打开文件时要小心,因为如果指定的文件已经存在,Python将返回文件对象前清空文件#注:Python只能将字符串写入文本文件。要将数值数据存储到文本文件中,必须先使用函数str()将其转换为字符串格式#10.2.2写入多行
filename ='programming.txt'withopen(filename,'w')as file_object:
file_object.write("I love programming.\n")
file_object.write("I love creating new games.\n")#要让每个字符串都独占一行,需要在write()语句中包含换行符withopen(filename)as file_object:
content = file_object.read()print(content)#10.2.3附加到文件#write_message.py
filename ='programming.txt'withopen(filename,'a')as file_object:
file_object.write("I also love finding meaning in large datasets.\n")
file_object.write("I love creating apps that can run in a croser.\n")withopen(filename,'r')as file_object:
content_1 = file_object.read()print(content_1)
第十章读书笔记10.2写入文件#coding:gbk#10.2.1写入空文件#write_message.oyfilename = 'programming.txt'with open(filename,'w') as file_object: file_object.write("I love programming.") with open(filename) as file_object: content = file_object.read() print(