创建一个新文件,文件名包含循环变量,python [英] Creating a new file, filename contains loop variable, python

查看:557
本文介绍了创建一个新文件,文件名包含循环变量,python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在循环上运行一个函数,并且要将输出存储在不同的文件中,以便文件名包含循环变量.这是一个示例

I want to run a function over a loop and I want to store the outputs in different files, such that the filename contains the loop variable. Here is an example

for i in xrange(10):
   f = open("file_i.dat",'w')
   f.write(str(func(i))
   f.close()

如何在python中做到这一点?

How can I do it in python?

推荐答案

只需使用+str构造文件名.如果需要,您还可以使用旧式新格式这样做,因此文件名可以构造为:

Simply construct the file name with + and str. If you want, you can also use old-style or new-style formatting to do so, so the file name can be constructed as:

"file_" + str(i) + ".dat"
"file_%s.dat" % i
"file_{}.dat".format(i)

请注意,您当前的版本未指定编码(您应该),并且在错误情况下无法正确关闭文件(with语句这样做):

Note that your current version does not specify an encoding (you should), and does not correctly close the file in error cases (a with statement does that):

import io
for i in xrange(10):
   with io.open("file_" + str(i) + ".dat", 'w', encoding='utf-8') as f:
       f.write(str(func(i))

这篇关于创建一个新文件,文件名包含循环变量,python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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