附加数据未写入文件

时间:2013-12-06 06:58:21

标签: python append

我是编程新手,正在尝试编写一个程序来判断一个家庭是否高于或低于贫困水平。 report4data和report4file是全局变量,report4data从文件读取,report4file写入同一文件。

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)

我收到了一个追加错误但我在appedpovolevel函数中创建了一个列表,并附加到列表然后尝试写入该文件,我不再收到错误但它不起作用。我想也许因为我从一个循环中调用appendpovolevel它没有工作,但我认为如果是这样的话,至少有一条线会附加上面或下面的贫困水平。

我正在使用Python 3.x

1 个答案:

答案 0 :(得分:2)

这里有两个明显的问题:

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

首先,您不必要地创建嵌套列表(.readlines()已经返回列表)。然后,.append()修改其就地调用的列表。它不会返回新列表。因此,第一行将appendata设置为None,当您将其写入文件时,没有任何反应。

相反,做一些像

这样的事情
report4list = report4data.readlines()
report4list.append(AorB+"Poverty level")
report4file.writelines(report4list)

除此之外,您发布的代码对我来说非常混乱/困惑。您的程序逻辑似乎随机分布在各个函数中,使代码很难遵循。

我会尝试以不同的方式解决问题,将程序逻辑的每个部分封装在自己的函数中,使用更多令人回味的变量名称(尽我所能,因为我不知道你有什么数据在你的文件中完全):

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")
相关问题