正文
Python 文件writelines() 方法和处理双层列表
小程序:扫一扫查出行
【扫一扫了解最新限行尾号】
复制小程序
【扫一扫了解最新限行尾号】
复制小程序
概述
writelines() 方法用于向文件中写入一序列的字符串。
这一序列字符串可以是由迭代对象产生的,如一个字符串列表。
换行需要制定换行符 \n。
语法
writelines() 方法语法如下:
fileObject.writelines( [ str ])
data = ['a','b','c']
with open("data.txt","w") as f:
f.writelines(data)
输出:
对于双层列表中的数据
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)
输出:
部分内容来自网络