Am trying to loop through a range of variables and write them to output files on new lines.

I have researched and tried f.write, print(), printf, and f'.

Code is returning frequent syntax error or i am passing too many arguments or cannot concatenate strings and integers.

DEFINE VARIABLES

House = range(0,40,10) .

LOOP THROUGH EACH VARIATION:

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 Answers

1
Devesh Kumar Singh On

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