首页 > 解决方案 > 从文本文件 Python 中查找最新的列

问题描述

我正在做一个项目,该项目可以让我更有效地记录我的收入/支出,但我似乎无法找到如何在给定文本文件中找到最新列,请记住代码是原型,因为我只大约一个小时前开始研究它。

f = open('Money.txt','a')

while True:
    while True:
        OP = input("Operator: ")
        if OP == "+" or OP == "-":
            break
        else:
            print("Invalid Operator, please try again.\n\n")
    while True:
        try:
            MA = int(input("Money amount: "))
            break
        except ValueError:
            print("Numeric value only.\n\n")
    while True:
        if OP == "+":
            MV = input("Where you recived the money: ")
            break
        elif OP == "-":
           MV = input("Where you spent the money: ")
           break
    while True:
        C = input('\n\nIs "' + OP + "/" + str(MA) + "/" + MV + '" correct: ')
        if C.lower() == "yes":
            break
        elif C.lower() == "no":
            print("Restarting...\n\n")
            break
        else:
            print("Invalid response, try again.\n\n")
    if C.lower() == "yes":
        break
    elif C.lower() == "no":
        continue

fs = OP + " $" + str(MA) + " / " + MV
f.write('\n' + fs)
f.close()
print("Values written.")

# "abcde!mdam!dskm".split("/", 2) - basic idea of the code ill use after i figure out how to get latest column from text file

我不太擅长编程,所以如果您看到改进我的代码的公然方法,请继续分享它,任何帮助都会得到帮助!

标签: python

解决方案


我想通了,它可能不是最有效的方法,但它有效:

fc = f.readlines()
l = -1
for line in fc:
    l += 1

然后,您可以使用“l”来分割您的列表并执行您需要对其执行的任何操作。

注意:您需要将“f = open('Money2.txt','a')”更改为“f = open('Money2.txt','r+')”


推荐阅读