python: ValueError: I/O operation on closed file
<p>My code:</p>

<pre><code>with open('pass.txt') as f:
        credentials = dict([x.strip().split(':') for x in f.readlines()]) # Created a dictionary with username:password items

        name_input = input('Please Enter username: ')

        if name_input in credentials:  # Check if username is in the credentials dictionary

            name_input = input('Please Enter new username: ')



        f.write(name_input)
        f.write(":")
        pass_input = input('Please Enter password: ')
        f.write(pass_input)
        f.write("\n")
        f.close()

        print('Registered')
</code></pre>

<p>I am getting this error: </p>

<pre><code>Traceback (most recent call last):
  File "silwon.py", line 146, in &lt;module&gt;
    f.write(name_input)
ValueError: I/O operation on closed file.
</code></pre>

<p>also how to use sys.exit after the user enters the same username 3 times?</p>

<p>Every file operation in Python is done on a file opened in a certain mode. The mode must be specified as an argument to the open function, and it determines the operations that can be done on the file, and the initial location of the file pointer.</p>

<p>In your code, you have opened the file without any argument other than the name to the open function. When the mode isn't specified, the file is opened in the default mode - read-only, or <code>'r'</code>. This places the file pointer at the beginning of the file and enables you to sequentially scan the contents of the file, and read them into variables in your program. To be able to write data into the file, you must specify a mode for opening the file which enables writing data into the file. A suitable mode for this can be chose from two options, <code>'w'</code> or <code>'w+'</code> and <code>'a'</code> or <code>'a+'</code>. </p>

<p><code>'w'</code> opens the file and gives access to the user only to write data into the file, not to read from it. It also places the pointer at the beginning of the file and overwrites any existing data. <code>'w+'</code> is almost the same, the only difference being that you can read from the file as well.</p>

<p><code>'a'</code> opens the file for writing, and places the file pointer at the end of the file, so you don't overwrite the contents of the file. <code>'a+'</code> extends the functionality of <code>'a'</code> to allow reading from the file as well.</p>

<p>Use an appropriate mode of opening the file to suit your requirement, and execute it by modifying the open command to <code>open('pass.txt', &lt;mode&gt;)</code>.</p>

python python-3.4