Python从文件中读取命令

时间:2015-03-06 02:52:56

标签: python file input line

我是python的新手,我正在尝试打开一个文件,查看其内容,并根据这些内容做一些事情。

例如,如果文件包含:

Buy 100 20.00
Buy 400 10.00
Sell 200 28.00

我如何一次读取一行文件,将每个项目分配给变量,并根据这些变量执行操作?

例如,我读了第一行,

 command = Buy
 quantity = 100
 price = 20.00

我做了一些事情,然后阅读下一行

command = Buy
quantity = 400
price = 10.00

希望这很清楚,谢谢

2 个答案:

答案 0 :(得分:3)

def buy(num, value):
    # a sample Buy function
    print("Buy {} at {}".format(num, value))

def sell(num, value):
    # a sample Sell function
    print("Sell {} at {}".format(num, value))

# command dispatch table - get function based on string
command = {"Buy": buy, "Sell": sell}

def main():
    with open("file.txt") as inf:
        for line in inf:
            cmd, num, val = line.split()
            command[cmd](int(num), float(val))

if __name__ == "__main__":
    main()

答案 1 :(得分:2)

你可以这样做:

with open("test.txt", "r") as f:
    for a_line in f:
        command, quantity, price = a_line.split()
        print(command, quantity, price)
        # do what you want with these values here
        # please note that quantity and price are strings. need to 
        # change them to float if you want to do some calculations.