【问题标题】:Creating a new file, filename contains loop variable, python创建一个新文件,文件名包含循环变量,python
【发布时间】: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 中做到这一点?

【问题讨论】:

    标签: python file


    【解决方案1】:

    只需用+str 构造文件名。如果需要,也可以使用old-stylenew-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))
    

    【讨论】:

      【解决方案2】:

      使用f = open("file_{0}.dat".format(i),'w')。实际上,您可能想要使用类似f = open("file_{0:02d}.dat".format(i),'w') 的东西,它将对名称进行零填充以将其保持为两位数(因此您会得到“file_01”而不是“file_1”,这对于以后的排序很有用)。见the documentation

      【讨论】:

        【解决方案3】:

        i 变量连接成一个字符串,如下所示:

        f = open("file_"+str(i)+".dat","w")
        

        f = open("file_"+`i`+".dat","w") # (`i`) - These are backticks, not the quotes.
        

        有关其他可用技术,请参阅 here

        【讨论】:

        • 抱歉,它已被编辑 - 当第二个示例有引号而现在有反引号时,我投了反对票
        【解决方案4】:

        试试这个:

        for i in xrange(10):
           with open('file_{0}.dat'.format(i),'w') as f:
               f.write(str(func(i)))
        

        【讨论】:

          【解决方案5】:

          使用 f 字符串

          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)}')
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-05-02
            • 2016-02-23
            • 1970-01-01
            • 1970-01-01
            • 2022-06-16
            • 2019-12-09
            相关资源
            最近更新 更多