Python循环读取外部文件时else语句重复输出的问题及解决
问题背景
- 现有两个文件:外部文件
tasks.txt和主文件task_manager.py tasks.txt的单行内容格式示例:admin, Register Users with taskManager.py, Use taskManager.py to add the usernames and passwords for all team members that will be using this program., 10 Oct 2019, 20 Oct 2019, No- 字段含义(以逗号加空格分隔):用户名、任务标题、任务描述、分配日期、截止日期、任务完成状态
需求与初始问题
需求:读取tasks.txt,当用户名匹配时按指定格式打印对应行;无匹配用户名时,仅打印一次You have no tasks at the moment。
初始代码使用for循环读取文件时,else语句会针对tasks.txt的每一行重复输出提示信息,代码如下:
username = "admi" f2 = open('tasks.txt', 'r') for line in f2: line3_split = line.split(', ') if line3_split[0] == username: user_format = f""" Task: {line3_split[1]} Assigned to: {line3_split[0]} Date assigned: {line3_split[3]} Due date: {line3_split[4]} Task complete? {line3_split[5]} Task description: {line3_split[2]} """ print(user_format) else: print("You have no tasks at the moment.") f2.close()
改进尝试与新问题
修改代码先判断用户名是否存在于文件内容中,解决了重复输出问题,但for循环失效——原因是文件读取一次后指针停在末尾,无法再次读取。修改后的代码:
username = "admn" f2 = open('tasks.txt', 'r') is_user = f2.read() if username in is_user: for line in f2: line3_split = line.split(', ') if line3_split[0] == username: user_format = f""" Task: {line3_split[1]} Assigned to: {line3_split[0]} Date assigned: {line3_split[3]} Due date: {line3_split[4]} Task complete? {line3_split[5]} Task description: {line3_split[2]} """ print(user_format) else: print("You have no tasks at the moment.") f2.close()
最终解决方案
使用.seek(0,0)重置文件指针到文件开头,实现二次读取文件,解决所有问题。最终代码:
username = "admin" f2 = open('tasks.txt', 'r') is_user = f2.read() if username in is_user: f2.seek(0,0) for line in f2: line3_split = line.split(', ') if line3_split[0] == username: user_format = f""" Task: {line3_split[1]} Assigned to: {line3_split[0]} Date assigned: {line3_split[3]} Due date: {line3_split[4]} Task complete? {line3_split[5]} Task description: {line3_split[2]} """ print(user_format) else: print("You have no tasks at the moment.") f2.close()
内容的提问来源于stack exchange,提问作者tekkyprograms
相关产品推荐
相关产品推荐

