我是 python 编程的新手,需要一些基本文件 I/O 和列表操作方面的帮助。
目前我有一个包含这些元素的列表:
['taylor343', 'steven435', 'roger101\n']
我需要做的是将每一行打印到新的文本文件中,文本文件中只有 1 个元素,如下所示:
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")
我怎样才能让它把列表的每一行都写入新的文本文件(不仅仅是一个)
谢谢
最佳答案
您需要打开每个要写入的新文件。举个简单的例子:
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 - 将列表的元素打印到python中的单独文本文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6673092/