【问题标题】:Using items in list to create file name - for loop使用列表中的项目创建文件名 - for 循环
【发布时间】:2017-10-24 17:02:32
【问题描述】:
  • 我有一个用于 for 循环的列表。
  • 列表中的每个项目都有执行的操作,但我想为发生的事情写一个文件。
  • 如何使用 for 循环中的变量为列表中的每个项目创建特定的文件名?
mylist = ['hello', 'there', 'world']
for i in mylist:
    outputfile = open('%i.csv', 'a')
    print('hello there moon', file=outputfile)
  • 我使用%i 表示列表中的各个项目是否正确?

【问题讨论】:

标签: python loops variables for-loop


【解决方案1】:

您可以使用format() 来做您需要的事情,如下所示:

mylist = ['hello', 'there', 'world']

for word in mylist:
    with open('{}.csv'.format(word), 'a') as f_output:
        print('hello there moon', file=f_output)    

使用with 之后也会自动关闭您的文件。

format() 有许多可能的特性来允许各种字符串格式化,但简单的情况是用一个参数替换 {},在你的例子中是 word

【讨论】:

    【解决方案2】:

    您应该使用%s,因为列表中的项目是字符串。

    outputfile = open('%s.csv' % i, 'a')
    

    【讨论】:

      【解决方案3】:

      使用以下代码。

      mylist = ['hello', 'there', 'world']
      for i in mylist:
          outputfile = open('%s.csv'%i, 'a')
          print('hello there moon', file=outputfile)
          outputfile.close()
      

      【讨论】:

        【解决方案4】:
        mylist = ['hello', 'there', 'world']
        for item in mylist:
           with open('%s.txt'%item,'a') as in_file:
              in_file.write('hello there moon')
        

        【讨论】:

          【解决方案5】:

          使用 f 字符串

          使用来自 OP 的代码

          mylist = ['hello', 'there', 'world']
          for i in mylist:
          
              # open the file
              outputfile = open(f'{i}.csv', 'a')
          
              # write to the file
              print('hello there moon', file=outputfile)
          
              # close the file
              outputfile.close()
          

          使用with关闭文件

          mylist = ['hello', 'there', 'world']
          for i in mylist:
          
              with open(f'{i}.csv', 'a') as outputfile:
          
                  outputfile.write('hello there moon')
          

          【讨论】:

            猜你喜欢
            • 2018-06-04
            • 2020-11-14
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-03-24
            • 1970-01-01
            • 2021-05-12
            • 2011-01-04
            相关资源
            最近更新 更多