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())
普天同庆 #该文件现在是普天同庆和花好月圆,说明写会覆盖
花好月圆
>>>
版权声明:本文为wang_weina原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。