Python 从文件中读取命令
Python Reading Commands from File
我是 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
希望清楚,谢谢
您可以进行如下操作:
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.
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()
我是 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
希望清楚,谢谢
您可以进行如下操作:
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.
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()