Python 如何在一行中写入打印字符串变量和循环范围变量

Python 如何在一行中写入打印字符串变量和循环范围变量,python,Python,我试图循环一系列变量,并将它们写入新行上的输出文件 我研究并尝试了f.write、print()、printf和f' 代码返回频繁的语法错误,或者我传递了太多参数,或者无法连接字符串和整数 定义变量 House=范围(0,40,10) 循环通过每个变体: casenumber = 0 #used in the filename for ham in House: # CREATE INDIVIDUAL YML (TEXT) FILES

我试图循环一系列变量,并将它们写入新行上的输出文件

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

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

定义变量

House=范围(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()

这应该适合您,我想您应该将编号
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))

f.write中的
House
(“我家有这么多垃圾罐头”,House)
可能也是
ham
文件。write只需要一个参数,所以你应该将它拆分为对
f.write
的多个调用。不需要拆分对
f.write()的调用,只需要使用
str.format()
f-string
。我认为OP期望
f.write()
的行为与
print('something value is',something)
相同。