File Input/Output 9/9 Why does the solution like this?


#1

This is my code(and it worked):

with open("text.txt", "w") as my_file:
  my_file.write("My Data!")
  if my_file != my_file.closed:
    my_file.close()
    print my_file.closed

And this is the Codecademy solution:

with open("text.txt", "w") as my_file:
  my_file.write("My Data!")
  
if not file.closed:
  file.close()

print my_file.closed

Look at how they have written he code in the if statement:

I dont mind the IF NOT part, but why have they written file.closed instead of my_file.closed ?
And they do it one more time when they call .close on it below the if statement!
But when they print, they write my_file.closed


#2

Their example is all kinds of wrong.
They’re also missing the point of a while statement

A correct way of doing that (I’d call your code wrong as well due to testing whether a file is open when it obviously is, and closing it twice… in your defence the exercise does suggest something along those lines)

with open("text.txt", "w") as my_file:
    my_file.write("My Data!")
print my_file.closed

Or to demonstrate what the with-statement does:

with open("text.txt", "w") as my_file:
    my_file.write("My Data!")
    print "is the file closed while inside the context manager?", my_file.closed
print "is the file closed after exiting the context manager?", my_file.closed

#3

Ok so basically go from:

with open("text.txt", "w") as my_file:
  my_file.write("My Data!")
  if my_file != my_file.closed:
    my_file.close()
  print my_file.closed

To:

with open("text.txt", "w") as my_file:
  my_file.write("My Data!")
  
print my_file.closed

Basically drop the if statement???

But isn’t the whole point to check IF its closed or not?


#4

If open succeeded and you haven’t closed that file since, then it is open. There is nothing to check.
Also note that the file object isn’t a boolean, so this comparison is always going to result in True:

my_file != my_file.closed
 ^ file object     ^ boolean

#5

Ok so what should I do so that I pass that lesson when Codecademy ask us to solve the problem like this:

Below your withas code, do two things:

  • Check if the file is not closed .
  • If that’s the case, call .close() on it.
  • (You don’t need an else here, since your if statement should do nothing if closed is True .)
  • After your if statement, print out the value of my_file.closed to make sure your file is really closed.

Question

How can I check if my file is closed or not?

Answer

The value stored in the file’s closed attribute will be either True or False , so we can directly check it in our if statement, like this:
if file_var.closed:
However, we want to check if it is not closed, so you’ll need to alter the expression slightly. Then, be sure to indent the code you want inside of your if statement using 2 spaces.


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.