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: 
After asking the input for `student_id`, I suggest to iterate the `file` first to check for existed `student_id` in each `line` using list comprehension as flag.

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

```

If list is not exists or False, you can continue asking for other input before writting to the file.

```
with open('testfile.txt', 'r+') as file:
    student_id = input('Input student ID : ')
    found = [line for line in file if student_id in line]
    if found: 
        print("There is already a student with the same ID")
    else:
        name = input('Input student name : ')
        mobile = input('Input mobile number : ')
        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