该代码仅打印文本文件的第一行

问题描述

我认为问题出在嵌套函数dis_Details()中 我试图做的是打印文本文件中的每一行,但是当我运行代码时,它只会在文本文件中运行1索引,并且不会超出该范围。(如果文本文件的下一行没有任何内容,则应该停止,但无法正常工作)

def Customer_Details():

    Name = input('Enter the customer name: ')
    Phone = input('Enter the customer phone number: ')

    with open('Customer Details.txt','+a')as Details:
        Details.write('\n'+Name)
        Details.write(','+Phone)
        
    Details.close()

    print('Data Saved... Returning to Main menu')
    time.sleep(1)
    Main()


def Recall_Details():

    def dis_Details():
        Empty = False
        num = 0
        with open('Customer Details.txt','r+')as details:
        
            for line in details:

                Info = details.readlines()

                if not line:
                    break
                else:
                    print('Customer '+str(num)+': '+Info[num])
                    num += 1
                    
                
        details.close()

            

    Choice = input('would you like to check customer Details?(y): ')
    if Choice == 'y':

        dis_Details()
    ```

解决方法

with open('Customer Details.txt','r+') as details:
    for num,line in enumerate(details.read().split("\n")):
        print('Customer ' + str(num) + ': '+ line)

也许是这样吗?

,

您可能想要获取读取行数组,然后对其进行处理,在这种情况下,您只需要:

def dis_details(path):
    lines = []
    with open(path) as file:
        lines = file.read().splitlines()
    for i in range(len(lines)):
        print(f"Costumer {i}: {lines[i]}")