Skip to main content
 首页 » 编程设计

python之为什么我的 readline 不前进到下一行

2025年02月15日9davidwang456

每当我的方法应该前进到我正在导入的 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) 

客户.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 

交易.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 

请您参考如下方法:

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

opens the customers file, sets a variable to whatever line we are on

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

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

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