-1

in the function im trying to search for a specific person in a file if the preson is in not the file ill give a print . if its in the file ill create a new file without the person . for some reseon it doesn't get inside the for loop after the else statement i dont know why..please help
the file f is like this :

  • employee_id: 305078495
  • Name: hadar
  • phone: 0525676380
  • age: 27
  • employee_id: 305078487

  • Name: shir

  • phone: 0525676340

  • age: 27

    def delete_employee_manually():
        employee_id1 = raw_input("Enter the ID number to delete")
        name1 = raw_input("Enter employee name to delete")
        phone1 = raw_input("Enter phone to delete")
        age1 = raw_input("Enter age to delete")
        delete_list = [str(employee_id1) , str(name1) ,str(phone1)  , str(age1)]
    
        f=open(r'D:\Employee.txt',"r") 
        output=open(r'D:\Employee_after_delete.txt',"w+")
    
        if name1 not in f.read():
           print name1, "is not on the Employee list"
        else:
            for line in f:
                if not any(delete_list in line for delete_list in delete_list):
                    output.write(line)
                    print name1, "as been deleted from the Employee list!"
    
Hadar Pinko
  • 11
  • 1
  • 1
  • 2
  • The problem is that `f.read()` reads in the entire file, all the way to the end. Then the for-loop under the `else` finds nothing to read, and terminates immediately. Store the lines in a list so you can scan them twice. – alexis Dec 09 '18 at 09:14
  • PS. Why are you learning with Python 2? Switch to Python 3 now. – alexis Dec 09 '18 at 09:17

1 Answers1

-1

You are trying to use the same file handler twice. Files should only be read once.

f = open('somefile.txt','r')
print 'a' in f.read()  #checking this membership condition consumes the handler #prints True if a is in the file
print f.read()  #handler at end of file. prints ''
print 'a' in f.read() #prints false now.

You should read and store the file contents instead in a variable. As a good habit, use the with context manager to read files.

with open('somefile.txt', 'r') as f:
    content = f.read()

print 'a' in content #assuming this prints True
print 'a' in content #prints true again
Paritosh Singh
  • 6,034
  • 2
  • 14
  • 33