【发布时间】:2012-09-24 07:30:34
【问题描述】:
我想在循环上运行一个函数,并且我想将输出存储在不同的文件中,这样文件名就包含循环变量。这是一个例子
for i in xrange(10):
f = open("file_i.dat",'w')
f.write(str(func(i))
f.close()
我如何在 python 中做到这一点?
【问题讨论】:
我想在循环上运行一个函数,并且我想将输出存储在不同的文件中,这样文件名就包含循环变量。这是一个例子
for i in xrange(10):
f = open("file_i.dat",'w')
f.write(str(func(i))
f.close()
我如何在 python 中做到这一点?
【问题讨论】:
只需用+ 和str 构造文件名。如果需要,也可以使用old-style 或new-style formatting 这样做,因此文件名可以构造为:
"file_" + str(i) + ".dat"
"file_%s.dat" % i
"file_{}.dat".format(i)
请注意,您当前的版本未指定编码 (you should),并且在错误情况下不会正确关闭文件(with 语句 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))
【讨论】:
使用f = open("file_{0}.dat".format(i),'w')。实际上,您可能想要使用类似f = open("file_{0:02d}.dat".format(i),'w') 的东西,它将对名称进行零填充以将其保持为两位数(因此您会得到“file_01”而不是“file_1”,这对于以后的排序很有用)。见the documentation。
【讨论】:
将i 变量连接成一个字符串,如下所示:
f = open("file_"+str(i)+".dat","w")
或
f = open("file_"+`i`+".dat","w") # (`i`) - These are backticks, not the quotes.
有关其他可用技术,请参阅 here。
【讨论】:
试试这个:
for i in xrange(10):
with open('file_{0}.dat'.format(i),'w') as f:
f.write(str(func(i)))
【讨论】:
f,变量在字符串引号内,由{} 包围。
f"file_{i}.dat"range 而不是 xrange
f.write(f'{func(i)}') 或 f.write(str(func(i)))
def func(i):
return i**2
for i in range(10):
with open(f"file_{i}.dat", 'w') as f:
f.write(f'{func(i)}')
【讨论】: