在python中将列表元素打印到单独的文本文件中 [英] Printing out elements of list into separate text files in python

查看:1549
本文介绍了在python中将列表元素打印到单独的文本文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



目前我有一个列表,它包含了这些元素在这里:

  ['taylor343','steven435','roger101\\\
']

我需要做的是在文本文件中只用1个元素将每一行打印到新的文本文件中,如下所示:

 
file1.txt
taylor343

file2.txt
steven435

file3.txt
roger101

我正在尝试使用循环,但是我只能输出到1个文本文件

 列表中的x:
output.write(x +\\\

我怎样才能把它的每一行列表写入新的文本文件(不只是一个)



谢谢

解决方案

您需要打开每个要写入的新文件。作为一个简单的例子:

  items = ['taylor','steven','roger'] 
文件名= ('文件','文件2','文件3']

为项目,文件名在zip(项目,文件名):
与开放(文件名,'w')作为输出:
output.write(item +'\\\
')


Im new to python programming and need some help with some basic file I/O and list manipulation.

currently i have a list (s) that has these elements in it:

['taylor343', 'steven435', 'roger101\n']

what i need to do is print each line into new text files with only the 1 element in the text files as shown below:

file1.txt
taylor343

file2.txt
steven435

file3.txt
roger101

Im currently trying to work with this using a loop but i can only output into 1 text file

for x in list:  
    output.write(x+"\n")

How can i get it to write every single line of list into new text files (not just one)

Thank you

解决方案

You need to open each new file you want to write into. As a quick example:

items = ['taylor', 'steven', 'roger']
filenames = ['file1', 'file2', 'file3']

for item, filename in zip(items, filenames):
    with open(filename, 'w') as output:
        output.write(item + '\n')

这篇关于在python中将列表元素打印到单独的文本文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆