概述

writelines() 方法用于向文件中写入一序列的字符串。

这一序列字符串可以是由迭代对象产生的,如一个字符串列表。

换行需要制定换行符 \n。

语法

writelines() 方法语法如下:

fileObject.writelines( [ str ])

data = ['a','b','c']
with open("data.txt","w") as f:
    f.writelines(data)

输出:

Python  文件writelines() 方法和处理双层列表

 对于双层列表中的数据

data = [ ['a','b','c'],['a','b','c'],['a','b','c']]
with open("data.txt","w") as f:
    for i in data:  # 对于双层列表中的数据
        i = str(i).strip('[').strip(']').replace(',', '').replace('\'', '') + '\n'  # 将其中每一个列表规范化成字符串
        f.write(i)

输出:

Python  文件writelines() 方法和处理双层列表

 

 部分内容来自网络

 

相关文章:

  • 2021-10-09
  • 2021-05-27
  • 2021-06-23
  • 2021-08-09
  • 2021-12-08
  • 2021-09-11
  • 2022-12-23
  • 2021-11-04
猜你喜欢
  • 2022-01-02
  • 2022-01-03
  • 2021-09-29
  • 2022-12-23
  • 2021-11-02
  • 2021-08-18
  • 2021-11-29
相关资源
相似解决方案