为什么我的readline不会进入下一行?

时间:2017-04-18 01:54:02

标签: python readline

每当我的方法应该进入我导入的txt文件中的下一行时,他们决定继续使用相同的行而不是前进到文档中的下一行。

DUMMY = 9999

def readMaster():
     #opens the customers file, sets a variable to whatever line we are on
     infile=open("customers.txt", 'r')
     line=infile.readline()[:-1]

#checks if entered ID is valid. If it is, return their name and balance. if not, return garbage.
     if line!=(""):
         masterID,masterName,balance=line.split(",")
         return int(masterID),masterName,int(balance)
     else:
         masterID=DUMMY
         return masterID,"",0
     infile.close()


 def readTransaction():
     #opens the transactions files
     infile=open("transactions.txt","r")

     #scans through the transactions file. If Item ID is found, return that line
     #if it isn't, return garbage variables.
     line=infile.readline()[:-1]
     if line!=(""):
        itemID,itemName,cost=line.split(",")
        return int(itemID),itemName,int(cost)

     else:
        itemID=DUMMY
        return itemID,"",0
     infile.close()

def updateRecords():

     #creates a new file for us to write to.
     outfile = open("new_master.txt", 'w')

     #pulls in any values we need for calculation

     masterID,masterName,balance = readMaster()
     itemID,itemName,cost=readTransaction()

     #checks to see if the customer's ID matches the ID of the service purchased. To avoid printing multiple lines
     #per person, we use a while loop to continue adding to the balance until the customer didn't buy the next item.
     #Then, asks for the next line in the transaction text.

     if int(itemID)==int(masterID):
         while int(itemID)==int(masterID):
             balance = balance+cost

             return int(itemID),itemName,int(cost)

     # Since the customers.txt and transactions.txt files are both sorted numerically, we check to see
     # if one is greater than the other. If it is, that means a customer didn't make any purchases, so we
      # print that person's line from customers.txt without updating it

    elif itemID>masterID:
         print(masterID+","+masterName+","+balance,file =outfile)


     # If we don't find any transactions for something, an error is printed.

    else:
         print("No record for item",itemID)


     print(masterID + "," + masterName + "," + balance, file=outfile)

     itemID,itemName,cost=readTransaction()

     #Then, we print the customer's ID, name, and new balance to the new text file

     print (masterID+","+masterName+","+balance,file = outfile)

Customers.txt移动

207,Ann Wyeth,120
215,David Fisher,89
412,Deb Washington,75
609,Lily Ahn,110
610,Dottie Sturgis, 39
1984,Leslie Jackson,109
1989,Taylor Grandview,55
1999,Roger Nelson,65
2112,Lee Geddy,99
5150,Valerie Edwards,45
7800,John Bongiovi,160

transactions.txt

207,Formal Styling,55
207,Partial Highlights,65
215,Haircut,29
610,Formal Styling,55
610,Accent Highlights,50
1999,Clipper Cut,19
2112,Haircut with Shampoo,39
5150,Haircut with Styling,45
5150,Partial Highlights,65
5150,Treatments,29
6792,Coloring,150
7800,Haircut,29

1 个答案:

答案 0 :(得分:1)

您没有循环文件的内容。在你的每个方法中你打开文件然后做一个readline,所以你似乎要求它重复打开文件并只读取第一行。例如,在readMaster您认为它在做:

  

打开客户文件,将变量设置为我们所在的行

但事实并非如此。你打开文件,读取它的一行,检查一个空字符串,然后在关闭文件之前返回一些元组。无论你多少次调用这种方法,它都只能读取第一行。

由于您基本上对两个文件执行相同类型的读取操作(为每个int(line[0]),line[1],int(line[2])返回line,因此您可以使用单个方法(如果您需要以不同方式处理,则可以使用基于文件名等的布尔开关。):

def readFile(filename):
    # returns data from specified file 
    with open(filename, 'r') as infile:
        lines = [line.trim() for line in infile.readlines()]

    lines = [(int(ln[0]),ln[1],int(ln[2])) for ln.split(',') in lines if ln else (masterID,'',0)]

    return lines

我不确定你期望什么样的输出,但我知道这可能是你想要的:

customers = r'c:\debug\customers.txt'
transactions = r'c:\debug\transactions.txt'
outputFile = r'c:\debug\new_master.txt'
def readFile(filename):
    DUMMY = 9999
    default = [DUMMY,'',0]
    # opens the customers file, and returns a list of tuple OR
    # opens the transactions file and returns a list of tuple
    with open(filename, 'r') as infile:
        lines = [line.strip().split(',') for line in infile.readlines()]
    lines = [ln[:3] if ln else default for ln in lines]
    return lines

def updateRecords():
    """
        checks to see if the customer's ID matches the ID of the service purchased. 
        To avoid printing multiple lines per person, add to the balance for each matching id.
    """
    #pulls in any values we need for calculation
    master = readFile(customers)
    trans = readFile(transactions)
    #creates a new file for us to write to.
    outfile = open(outputFile, 'w')
    for (id,name,bal) in master:
        balance = int(bal)
        balance += sum(int(itmCost) for (itmID,itmName,itmCost) in trans if itmID == id)
        # now we have the balance for THIS id from customer file
        if balance == int(bal):
            # If we don't find any transactions for something, an error is printed.
            # balance hasn't changed, no transaction for this customer, log to console
            print("No record for item {}".format(id))
        # update the new master file:
        outfile.write('{},{},{}\n'.format(id,name,balance))
    outfile.close()

并生成以下输出文件:

207,Ann Wyeth,240
215,David Fisher,118
412,Deb Washington,75
609,Lily Ahn,110
610,Dottie Sturgis,144
1984,Leslie Jackson,109
1989,Taylor Grandview,55
1999,Roger Nelson,84
2112,Lee Geddy,138
5150,Valerie Edwards,184
7800,John Bongiovi,189