I am trying to read in information from two different files. The first file, "database", is a file containing names of people and different parts of information about those people. Each person (and their info) is separated by line from the other people. The second file, "template", is a spam email template with numbered place-holders. My objective is to read the informational parts of the database into the numbered place-holders in the template and output a file for each person (3 people in the database). Thus, I should have 3 output files.

database = open("database", "r")

template = open("template", "r")

outfile1 = open("junk1", "w")

outfile2 = open("junk2", "w")

outfile3 = open("junk3", "w")

for line in database:
    part = line.split("|")
    title = part[0] #replaces #1
    firstname = part[1] #replaces #2
    lastname = part[2] #replaces #3
    address = part[3] #replaces #4
    city = part[4] #replaces #5
    state = part[5] #replaces #6
    zipcode = part[6] #replaces #7


for line in template:
    string = line

    for r in (("|1|",title),("|2|", firstname),("|3|", lastname),("|4|", address),("|5|", city),("|6|", state),("|7|", zipcode)):
        string = string.replace(*r)
    outfile1.write(string)
    outfile2.write(string)
    outfile3.write(string)          


outfile1.close()
outfile2.close()
outfile3.close()



database.close()
template.close()

I am wanting it to output to 3 DIFFERENT files. It currently outputs 3 files but each template output has name and info from only the last line. I need the first file to have template with the first person's info filled in, second file to contain second person's info, third file to contain third person's info.

1 Answers

2
furas On Best Solutions

You could use zip() to get data from database and file in which you have to write this data.

It could be something like this

database = open("database", "r")

# read all to memory to use it many times in `for` loop
template = list(open("template", "r"))

outfile1 = open("junk1", "w")
outfile2 = open("junk2", "w")
outfile3 = open("junk3", "w")

for line, output in zip(database, [outfile1, outfile2, outfile3]):
    part = line.split("|")
    title = part[0] #replaces #1
    firstname = part[1] #replaces #2
    lastname = part[2] #replaces #3
    address = part[3] #replaces #4
    city = part[4] #replaces #5
    state = part[5] #replaces #6
    zipcode = part[6] #replaces #7

    for string in template:
        for r in (("|1|", title),("|2|", firstname),("|3|", lastname),("|4|", address),("|5|", city),("|6|", state),("|7|", zipcode)):
           string = string.replace(*r)
        output.write(string)

outfile1.close()
outfile2.close()
outfile3.close()

With zip() you get first line from database with first file and you fill template using first data and save in first file, next you get second line from database with second file and you fill template using second data and save in second file, etc.