【问题标题】:Python Reading Commands from FilePython 从文件中读取命令
【发布时间】:2015-03-06 02:52:55
【问题描述】:

我是 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

希望这很清楚,谢谢

【问题讨论】:

  • 分割每一行有什么问题?

标签: python file input line


【解决方案1】:
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()

【讨论】:

    【解决方案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.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-29
      • 1970-01-01
      • 2011-11-18
      • 2017-12-15
      • 1970-01-01
      • 2018-12-06
      • 1970-01-01
      • 2016-05-09
      相关资源
      最近更新 更多