Hacking The Fender ~ ValueError: I/O operation on closed file. ~ HELP PLEASE

Traceback (most recent call last):
File “script.py”, line 39, in
new_passwords_obj.write(slash_null_sig)
ValueError: I/O operation on closed file.

Can anyone tell me how to fix this ?

Link ~ https://www.codecademy.com/courses/learn-python-3/projects/hacking-the-fender

import csv 
compromised_users = []
with open('passwords.csv') as password_file:
  password_csv = csv.DictReader(password_file)
  for password_row in password_csv:
    compromised_users.append(password_row['Username'])

with open('compromised_users.txt', 'w') as compromised_user_file:
  for user in compromised_users:
    compromised_user_file.write(user)

import json
with open('boss_message.json', 'w') as boss_message:
  boss_message_dict = {
    'recipent': 'The Boss',
    'message': 'Mission Success'
  }
  json.dump(boss_message_dict, boss_message)

with open('new_passwords.csv', 'w') as new_passwords_obj:
  slash_null_sig ="""
 _  _     ___   __  ____               
/ )( \   / __) /  \(_  _)            
) \/ (  ( (_ \(  O ) )(              
\____/   \___/ \__/ (__)             
 _  _   __    ___  __ _  ____  ____  
/ )( \ / _\  / __)(  / )(  __)(    \ 
) __ (/    \( (__  )  (  ) _)  ) D ( 
\_)(_/\_/\_/ \___)(__\_)(____)(____/ 
        ____  __     __   ____  _  _ 
 ___   / ___)(  )   / _\ / ___)/ )( \
(___)  \___ \/ (_/\/    \\___ \) __ (
       (____/\____/\_/\_/(____/\_)(_/
 __ _  _  _  __    __                
(  ( \/ )( \(  )  (  )               
/    /) \/ (/ (_/\/ (_/\             
\_)__)\____/\____/\____/
"""
new_passwords_obj.write(slash_null_sig)

Your with statement is followed by a suite of code for which it keeps the file open demarcated by a level of indentation. Once this suite is left the file will be closed for you.

Performing a write operation on a closed file leads to the error you received so you’ll need to adjust your code such that this action is performed whilst the file is open.

1 Like