码迷,mamicode.com
首页 > 编程语言 > 详细

Python之write与writelines区别

时间:2020-02-24 20:19:35      阅读:88      评论:0      收藏:0      [点我收藏+]

标签:cli   round   sequence   字符   error:   lines   enc   python   必须   

一、传入的参数类型要求不同:

  1、 file.write(str)需要传入一个字符串做为参数,否则会报错。

  write( "字符串"

1 with open(20200222.txt,w) as fo:
2     fo.write([‘a,b,c])
  #错误提示:TypeError: write() argument must be str, not list

 

  2、 file.writelines(sequence)可以有两种:字符串和字符序列,传入字符序列时,如果需要换行,则每个序列元素末尾需要有“\n”换行符才能达到所要输出的格式要求。

  注意 :writelines必须传入的是字符序列,不能是数字序列
       

  writelines( "字符串" )        writelines( "字符序列" )  

1 list1 = [a,1,3,4,5]
2 with open(20200222.txt,w) as fo:
3     fo.writelines(list1)
  #错误提示:TypeError: write() argument must be str, not int

   

1 list1 = [a,1,3,4,5]
2 with open(20200222.txt,w) as fo:
3     fo.writelines(list1)
   #正确传入参数!

1 with open(‘20200222.txt‘,‘w‘) as fo:
2 fo.writelines(今天是2020年2月22日星期六,\n) #注意,有个换行符,需要显式的加入换行符。
3 fo.writelines(我第一次在博客园上写博客!)

输出:

今天是2020年2月22日星期六,
我第一次在博客园上写博客!

 

Python之write与writelines区别

标签:cli   round   sequence   字符   error:   lines   enc   python   必须   

原文地址:https://www.cnblogs.com/yk_cjy2020/p/12346048.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!