简单了解Python write writelines区别

作者:小煜豆 时间:2023-06-16 14:00:28 

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

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

write( "字符串")


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

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

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

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


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

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

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

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

来源:https://www.cnblogs.com/yk_cjy2020/p/12346048.html

标签:Python,write,lines
0
投稿

猜你喜欢

  • golang 切片截取参数方法详解

    2024-04-25 15:31:22
  • Bootstrap编写一个兼容主流浏览器的受众巨幕式风格页面

    2024-05-02 17:31:43
  • python绘制堆叠条形图介绍

    2021-07-01 23:12:36
  • java编写创建数据库和表的程序

    2024-01-19 17:24:40
  • python中的decimal类型转换实例详解

    2022-05-01 15:05:21
  • 跟老齐学Python之总结参数的传递

    2021-12-16 18:17:24
  • 基于python实现删除指定文件类型

    2022-02-16 06:19:48
  • Python 实现过滤掉列表中唯一值

    2021-09-26 23:13:55
  • Python第三方常用模块openpyxl的简单介绍

    2021-05-28 16:10:09
  • python如何更新包

    2023-12-06 10:36:59
  • Python可变参数用法实例分析

    2022-01-20 04:24:55
  • Flask框架的学习指南之用户登录管理

    2023-01-16 18:43:45
  • Python的进程及进程池详解

    2021-05-18 08:51:46
  • WEB2.0网页制作标准教程(9)第一个CSS布局实例

    2008-02-19 19:05:00
  • linux mysql 报错:MYSQL:The server quit without updating PID file

    2024-01-22 08:40:47
  • Vue中的baseurl如何配置

    2024-05-09 15:10:46
  • Python爬取动态网页中图片的完整实例

    2023-11-12 20:29:27
  • Spark SQL常见4种数据源详解

    2024-01-18 09:07:21
  • Golang中Gin框架的使用入门教程

    2024-05-09 09:32:27
  • 浅析go中的map数据结构字典

    2024-05-22 10:13:05
  • asp之家 网络编程 m.aspxhome.com