写入文件:write( ) 和 writelines( )

1.write( )  str

>>> f=open(r'D:\python36\projects\text.txt')    #这里没有说明文件是用来读取还是写入的  
>>> words="争分夺秒\n"	  
>>> f.write(words)	  
Traceback (most recent call last):
  File "<pyshell#250>", line 1, in <module>
    f.write(words)
io.UnsupportedOperation: not writable
>>> f=open(r'D:\python36\projects\text.txt','w')        #这里说明该文件是用来写入的	  
>>> words="争分夺秒\n"	                                              #自己添加'\n'
>>> f.write(words)	                                     #write(str)的参数是str  
5                                                                #返回写入字符的个数
>>> f.close()	                          #写入文件后f.close(),文件才真正写入上面字符
>>> open(r'D:\python36\projects\text.txt','r').read()
'争分夺秒\n'
>>> print(open(r'D:\python36\projects\text.txt','r').read())
争分夺秒                                      #该文件内只有一个词争分夺秒,继续下面操作
>>> 

2.writelines( )  list

>>> f=open(r'D:\python36\projects\text.txt','w')	  
>>> words=['普天同庆\n','花好月圆\n']	                              #自己添加'\n'  
>>> f.writelines(words)	                   #wrotelines([list])参数是字符串组成的列表
>>> f.close()	  
>>> open(r'D:\python36\projects\text.txt','r').read()	  
'普天同庆\n花好月圆\n'
>>> print(open(r'D:\python36\projects\text.txt','r').read())	  
普天同庆                                  #该文件现在是普天同庆和花好月圆,说明写会覆盖
花好月圆
>>> 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值