如何从已拆分的.txt文件中获取多行并将其保存到不同的变量中

时间:2018-10-26 10:45:22

标签: python python-3.x

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)

我目前是从此开始的,但是它只打印出文本文件的最后一行。

2 个答案:

答案 0 :(得分:2)

尝试下面的代码,这将以字典的形式给您集体的结果。

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

答案 1 :(得分:1)

如果您希望打印每一行,则应在循环内添加一条打印语句。或保存它们以备后用。可能您想要这样的东西:

setTimeout(function(){
  $('#element').addClass('loading');
},1);

这将在循环期间打印每一行,并将所有字段保存在相对列表中。我在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]) 之外定义列表,以便可以从其他功能中获得它们。希望这会有所帮助。