I have a text file containing a list of names and job descriptions, for example:
Jim Salesman
Dwight Salesman
Pam Receptionist
Michael Manager
Oscar Accountant
I wanted to add the names and jobs of the persons who are "Salesman" to a list. But at the same time, I would also like to print out the full list of names and job descriptions. I wrote the following code for Python:
employee_file = open("employees.txt", "r")
matching = [sales for sales in employee_file if "Salesman" in sales]
print (matching)
print (employee_file.read())
employee_file.close()
The result I got is:
['Jim Salesman\n', 'Dwight Salesman\n']
Process finished with exit code 0
However, when I hash out the 2nd and 3rd lines of code, print(employee_file.read())
will generate the full list of names and job descriptions.
Can someone explain why print (employee_file.read())
is blank when the 2nd and 3rd lines of code are left in? I suspect it is because employee_file
is an empty variable. But I can't understand why that is the case.
Do I need to define a new variable employee_file2
and reopen the "employees.txt" file before executing the print function, for example:
employee_file2 = open("employees.txt", "r")
print (employee_file2.read())
Thanks in advance for your help.