要用python将列表的内容逐行写入文本文件中,需要使用内置函数open打开一个文本文件,然后循环写入,最后关闭。
代码如下:
import os
#定位文本文件所在的目录
sPath="d:\\"
os.chdir(sPath)
#打开文本文件
file1=open('test1.txt','w')
#获取列表
arr=['a','b','c']
#获取列表的总元素数
iLen=len(arr)
#循环写入
for x in arr:
file1.write(x+'\n')
#关闭文本文件,这个是关键,close要加括号
file1.close()
#打开文件夹查看结果
os.system('explorer.exe ' + sPath)


发表评论