简体   繁体   中英

appending data not being written to file

I'm new to programming and am trying to write a program that tells whether a family is above or below poverty level. report4data and report4file are global variables, report4data reads from a file and report4file writes to the same file.

def appendpovolevel(AorB):
    report4list = [report4data.readlines()]
    appendata = report4list.append(AorB+"Poverty level")
    report4file.write(str(appendata))

def report4(win):
    report4data
    for line in report4data.readlines():
        split = line.split()
        #equation to see if family is above or below poverty level
        povolevel = int(split[2])/int(split[1])

        #tells based on state if a family is above or below poverty level, if they fall below poverty level
        if split[3] == "HI":
            if povolevel >= 3600:
                appendpovolevel("Above")
            elif povolevel < 3600:
                appendpovolevel("Below")
        elif split[3] == "AK":
            if povolevel >= 3980:
                appendpovolevel("Above")
            elif povolevel < 3980:
                appendpovolevel("Below")
        else:
            if povolevel >= 3180:
                appendpovolevel("Above")
            elif povolevel < 3180:
                appendpovolevel("Below")

    report4data.close()
report4(win)

I was getting an append error but I created a list in the appedpovolevel function, and appended to the list and then tried to write to the file, I no longer get the error but it doesn't work.I thought that perhaps because I call appendpovolevel from a loop it wasn't working but I think if that were the case at least one line would have the above or below poverty level attached to it.

I'm using Python 3.x

Two obvious problems are here:

report4list = [report4data.readlines()]
appendata = report4list.append(AorB+"Poverty level")
report4file.write(str(appendata))

First, you're creating a nested list unnecessarily ( .readlines() already returns a list). Then, .append() modifies the list it's called on in-place. It doesn't return a new list. Therefore, the first line sets appendata to None , and when you write that to the file, nothing happens.

Instead, do something like

report4list = report4data.readlines()
report4list.append(AorB+"Poverty level")
report4file.writelines(report4list)

Aside from this, the code you've posted looks very confusing/confused to me. Your program logic appears to be spread across the functions randomly, making the code hard to follow.

I would try and approach the problem in a different way, encapsulating each part of the program logic in its own function, using somewhat more evocative variable names (as far as I could, because I don't know what data you have in your files exactly):

def read_report(filename):
    """Read file and return a list of the lines, split on whitespace"""
    with open(filename) as file:
        return [line.strip().split() for line in file]

def above_povertylevel(state, amount, divisor):
    """Check whether the quotient amount/divisor is above poverty level for a given state"""
    default = 3180
    levels = {"HI": 3600, "AK": 3980}
    return amount/divisor >= levels.get(state, default)

def update_report(infile, outfile):
    """Read report from infile, output updated report in outfile"""
    report = read_report(infile)
    with open(outfile, "w") as output:
        for dataset in report:
            if above_povertylevel(dataset[3], int(dataset[2]), int(dataset[1])):
                dataset.append("Above Poverty Level\n")
            else:
                dataset.append("Below Poverty Level\n")
            output.write(" ".join(dataset))

update_report("report4.txt", "output.txt")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM