Python多文件编写问题 [英] Python Multiple file writing question
本文介绍了Python多文件编写问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要python写多个文件名,每个文件名都不同于最后一个。我把它写在for循环中。因此,从Python程序编写的数据文件应如下所示:data1.txt,data2.txt,data3.txt。我怎么能在Python 3.2中做到这一点?显然,这个数字是唯一改变的文件名。
I need python to write multiple file names, each file name is different than the last. I have it writing in a for loop. Therefore the data files written from the Python program should look like this: data1.txt, data2.txt, data3.txt. How can I do this in Python 3.2? Obviously, the number is the only thing changing as the file name.
推荐答案
或者使用和
for i in range(10):
with open('data%i.txt' %i, 'w') as f:
f.write('whatever')
with
负责在出现问题时关闭文件。如果您在for循环中创建文件,这可能尤为重要,
with
takes care of closing the file if something goes wrong. This could be especially important if you are creating files in a for loop,
这篇关于Python多文件编写问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文