Question: I'm trying to ask for students' IDs and save it to a file, and if a student inputs an ID number that already exists in the file, it will print an invalid message.

I tried doing this by reading the file first and used if-else statement to check if the student ID is in the file or not. If it is, it will print the message; if not, it will add the student ID to the file. But for some reason, even when I input the same ID, it never shows the message and adds it to the file even though it already exists in the file. Where did I go wrong?

Here is my code:

```py
file = open('testfile.txt', 'r')
if student_id in file:
    print("There is already a student with the same ID")
else:
    names_file = open('testfile.txt', 'a')
    names_file.write(str(student_id) + ',' + name + ',' + str(mobile) + ',' + '0.0\n') 
    names_file.close()

```

Answer: 
The open file handle `file` is an iterable, but when you iterate over it (which is what the `in` operator does) you receive a line at a time. Your code is thus checking whether the file contains a line which is equal to `student_id`, not whether the string contained in that variable is contained anywhere in the file. The immediate problem is that the lines have their `\n` character left on the end of them, so unless your `student_id` also contains one, it will never match. But also, given that you write more than just the `student_id` field, you have to pick the line apart and check whether the match is in that particular field, and not e.g. in the phone number, or as a substring of a longer student ID.

A better fix is to only open the file once, anyway. Open it for appending, read it all, then if you find that you didn't want to write after all, abandon the effort; otherwise, append to the end.

```
with open('testfile.txt', 'r+') as file:
    for line in file:
        s_id, s_name, s_phone, s_grade = line.rstrip('\n').split(',')
        if student_id == s_id:
            print("There is already a student with the same ID")
            break
    else:
        file.write(str(student_id) + ',' + name + ',' + str(mobile) + ',' + '0.0\n') 

```
You opened the file but you haven't read the file,
Hence the if student\_id in file reads the object but not the file contents

Use this line

```py
#correct way to read file contents
file = open('testfile.txt', 'r').read()

```

Insted of this line

```py
#incorrect way
file = open('testfile.text', 'r')

```

Using .read() gives file contents, while plain open() gives file object

Also dont forget to close the file using

```py
file.close()

```

Close files after use or there might some errors

Hope this helps