Python Multiple file writing question

懵懂的女人 提交于 2019-12-13 14:36:04

问题


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.


回答1:


Alternatively using with

for i in range(10):
    with open('data%i.txt' %i, 'w') as f:
        f.write('whatever')

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,




回答2:


for i in range(10):
    f = open("data%d.txt" % i, "w")
    # write to the file
    f.close()

I'm not too familiar with Python 3.2 though, you might need to use the new string formatting like so: "data{0}.txt".format(i)



来源:https://stackoverflow.com/questions/6351007/python-multiple-file-writing-question

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!