[英]How to get multiple lines from a .txt file that have been split and to save them into different variables
def WorkLoad():
readWork=open("Todays_Work.txt","r")
for line in readWork.readlines():
WorkLine = line.split()
Order_No = WorkLine[0]
Deliver_Address = WorkLine[1]
Bay_Collection = WorkLine[2]
Stock = WorkLine[3]
print(WorkLine[0],"\n",WorkLine[1],"\n",WorkLine[2],"\n",WorkLine[3])
print(WorkLine)
I am currently started of with this but it only prints out the last line in the text file. 我目前从这里开始,但是它只打印出文本文件的最后一行。
Try below code this will give you collective result in the form of dictionary. 尝试下面的代码,这将以字典的形式给您集体的结果。
from collections import OrderedDict
result = OrderedDict() #creating a Ordered dictionary
#setting dictionary elements
result["Order_No"] = []
result["Deliver_Address"] = []
result["Bay_Collection"] = []
result["Stock"] = []
def WorkLoad(result):
readWork=open("Todays_Work.txt","r")
for line in readWork.readlines():
WorkLine = line.split()
result["Order_No"].append(WorkLine[0])
result["Deliver_Address"],append(WorkLine[1])
result["Bay_Collection"].append(WorkLine[2])
result["Stock"].append(WorkLine[3])
return result
data = Workload(result) #calling the workload function
print(data) #printing the data
If you wish to print each line, you should add a print statement inside the loop. 如果希望打印每一行,则应在循环内添加一条打印语句。 Or save them to a later use.
或保存它们以备后用。 Probably you want something like this:
可能您想要这样的东西:
Order_No = []
Delivery_Address = []
Bay_Collection = []
Stock = []
def WorkLoad():
readWork=open("Todays_Work.txt","r")
for line in readWork.readlines():
WorkLine = line.split()
Order_No.append(WorkLine[0])
Deliver_Address.append(WorkLine[1])
Bay_Collection.append(WorkLine[2])
Stock.append(WorkLine[3])
print(Order_No[-1], Deliver_Address[-1], Bay_Collection[-1], Stock[-1])
This prints each line during the loop and saves all the fields in the relative lists. 这将在循环期间打印每一行,并将所有字段保存在相对列表中。 I define the lists outside
WorkLoad
so they are available from other functions you may have. 我在
WorkLoad
之外定义列表,以便可以从其他功能中使用它们。 Hope this is helpful. 希望这会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.