2

I Created this code but i keep getting returned the error: ValueError: I/O operation on closed file What can I do to correct this mistake?

def eightBitStrings(n):
    if n > 0:
        #Assign variable to reference the name of the file... This shall be called EightBits...
        eightBits = "eightBits.txt"
        #Open file above
        outputFile = open(eightBits, "w")
        #Track the refrencenumber of values that we generate. 
        #As we generate values, we will decrement the value of counter
        counter = 0
        #As long as counter is LESS than n, we will need more numbers
        # Input random number, convert it to a string and then write it to the file on its own line
        #Add 1 to the counter since have generated a number
        
        while (counter < n):
            randomNumber = int(random.random() * 1001)
            outputFile.write(str(randomNumber) + "\n")
            counter = counter + 1
            outputFile.close()

Any suggestion would be appreciated

2
  • 1
    Please accept the edit proposed by Subbu VidyaSekar that will make your code easier to read. In essence, you should either (1) prepend each line of code with additional 4 spaces, *or* (2) put your code in between a pair of three backticks ( ``` ) on their own lines. Commented Oct 12, 2020 at 3:53
  • You're closing the file in a loop... It only needs to be closed once... Commented Oct 12, 2020 at 17:00

1 Answer 1

3

In your while loop you are closing the file, and then again trying to write it. Close the file after the loop ends

def eightBitStrings(n):
    if n > 0:
        #Assign variable to reference the name of the file... This shall be called EightBits...
        eightBits = "eightBits.txt"
        #Open file above
        outputFile = open(eightBits, "w")
        #Track the number of values that we generate. 
        #As we generate values, we will decrement the value of the counter
        counter = 0
        #As long as counter is LESS than n, we will need more numbers
        # Input random number, convert it to a string and then write it to the file on its own line
        #Add 1 to the counter since have generated a number
        
        while (counter < n):
            randomNumber = int(random.random() * 1001)
            outputFile.write(str(randomNumber) + "\n")
            counter = counter + 1
        outputFile.close()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.