如何解决该代码仅打印文本文件的第一行
我认为问题出在嵌套函数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]}")
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。