Python编程:从入门到实践第十章读书笔记10.2写入文件

第十章读书笔记10.2写入文件

#coding:gbk

#10.2.1写入空文件

#write_message.oy
filename = '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(content)

#调用open()时提供了两个实参,第一个实参是要打开的文件名,第二个实参('w')告诉Python要以写入模式打开这个文件
#打开文件时,可指定读取模式('r')、写入模式('w')、附加模式('a')或让你能够读取和写入(文件的模式('r+')。
#如果省略了模式实参,Python将以默认的只读模式打开文件。
#如果要写入的文件不存在,函数open()将自动创建它。
#然而,以写入('w')模式打开文件时要小心,因为如果指定的文件已经存在,Python将返回文件对象前清空文件

#注:Python只能将字符串写入文本文件。要将数值数据存储到文本文件中,必须先使用函数str()将其转换为字符串格式

#10.2.2写入多行

filename = 'programming.txt'

with open(filename,'w') as file_object:     
	file_object.write("I love programming.\n") 
	file_object.write("I love creating new games.\n")     #要让每个字符串都独占一行,需要在write()语句中包含换行符
	
with open(filename) as file_object:
	content = file_object.read()
	print(content)
	

#10.2.3附加到文件

#write_message.py
filename = 'programming.txt'

with open(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")
with open(filename,'r') as file_object:
	content_1 = file_object.read()
	print(content_1)


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值