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

时间:2019-04-25 15:22:39

标签: python

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

我研究并尝试了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()

1 个答案:

答案 0 :(得分:1)

This should work for you, I think you want to write the number ham to the file

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()

We will get 4 files here with the content in front of them

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

In addition, you can also use with statement to open your file, which will take care of closing your file for you as below.

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