Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: ValueError: I/O operation on closed file

My 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')

I am getting this error:

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

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

like image 531
Von Avatar asked Oct 12 '16 05:10

Von


2 Answers

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.

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 'r'. 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, 'w' or 'w+' and 'a' or 'a+'.

'w' 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. 'w+' is almost the same, the only difference being that you can read from the file as well.

'a' 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. 'a+' extends the functionality of 'a' to allow reading from the file as well.

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

like image 181
Saujas Vaduguru Avatar answered Oct 17 '22 23:10

Saujas Vaduguru


You need to define the operation that you are going to do with the file. In your case you want to write to the file so you need to select from the following modes: 'w', 'w+', 'a' or 'a+'

like image 23
Wasiullah Khan Avatar answered Oct 18 '22 00:10

Wasiullah Khan