首页 > 解决方案 > 如何在一行中一起写入打印字符串变量和循环范围变量

问题描述

我试图遍历一系列变量并将它们写入新行的输出文件。

我研究并尝试了 f.write、print()、printf 和 f'。

代码返回频繁的语法错误,或者我传递了太多参数或无法连接字符串和整数。

定义变量

House = range(0,40,10).

循环遍历每个变化:

casenumber = 0 #used in the filename
for ham in House:

                # CREATE INDIVIDUAL YML (TEXT) FILES
                casenumber = casenumber + 1
                filename = 'Case%.3d.yml' % casenumber
                f = open(filename, 'w')
                # The content of the file:

                f.write('My House has this many cans of spam', House)

                f.close()

标签: python

解决方案


这应该对你有用,我想你想把数字写到ham文件中

casenumber = 0 #used in the filename

#Iterate through the range
for ham in range(0,40,10):

    # CREATE INDIVIDUAL YML (TEXT) FILES
    casenumber = casenumber + 1
    filename = 'Case%.3d.yml' % casenumber
    f = open(filename, 'w')
    # The content of the file:

    #I assume you want to write the value of ham in the file
    f.write('My House has this many cans of spam {}'.format(ham))

    f.close()

我们将在这里得到 4 个文件,其内容在它们前面

Case001.yml #My House has this many cans of spam 0
Case002.yml #My House has this many cans of spam 10
Case003.yml #My House has this many cans of spam 20
Case004.yml #My House has this many cans of spam 30

此外,您还可以使用with语句打开文件,它将为您关闭文件,如下所示。

casenumber = 0 #used in the filename

#Iterate through the range
for ham in range(0,40,10):

    # CREATE INDIVIDUAL YML (TEXT) FILES
    casenumber = casenumber + 1
    filename = 'Case%.3d.yml' % casenumber
    with open(filename, 'w') as f:

        # The content of the file:
        #I assume you want to write the value of ham in the file
        f.write('My House has this many cans of spam {}'.format(ham))

推荐阅读