0

I am using python 2.x and I am going through company code, I found code that looks like:

filename = open('text.json', 'r')
# doSomething()
filename.close()

I am used to reading a file like so:

with open('text.json', 'r') as filename
# doSomething()

Can anyone explain what the difference is?

Ely Fialkoff
  • 642
  • 1
  • 5
  • 12
  • 1
    `as` is used with the `with` keyword to access the opened file in a context manager block. This will cause the file to be closed automatically after the block is executed. Using `as` in this case without a `with` is invalid syntax. – Owen Oct 24 '18 at 19:14
  • So does `open('text.json', 'r') as filename` not exist on its own? does it need the `with` to be valid? – Ely Fialkoff Oct 24 '18 at 19:16
  • Yes - that's not valid python – Owen Oct 24 '18 at 19:17

2 Answers2

0

The second one is usually used with a context manager, so you can do

with open('text.json', 'r') as filename:
    #your code

And you can access the file using the filename alias. The benefit of that is that the context manager closes the file for you.

If you do manually as your first example you would need to manually call filename.close() after you used it to avoid file locking

Rodolfo Donã Hosp
  • 1,037
  • 1
  • 11
  • 23
  • This does not answer my question. I will typically use `with` for my personal use. But I specifically wonder what is the difference between what I posted above. Thank you anyways. – Ely Fialkoff Oct 24 '18 at 19:15
  • If you are wondering if the output of them are different, they are not. You can use either way and your results will be the same. The difference is only on how you would use it, as i posted. Hope i understood your question correctly. Open on its own should not be used, as it returns a file object, and if you are not setting its value to anything, the object can't be used – Rodolfo Donã Hosp Oct 24 '18 at 19:17
0

When you open a file in python, you have to remember to close it when you're done.

So with your 1st line:

filename = open('text.json', 'r')

You'll need to remember to close the file.

The second version you have is typically used like this:

with open('text.json', 'r') as filename:
    #block of code

This will automatically close the file after the block of code is run.

The other difference is the way you're naming the file object as "filename". You end up with the same object in both, just naming it in two different ways.

AlphaTested
  • 1,037
  • 2
  • 15
  • 23