Question: Open Function in Python

I know how the function works in python, but this code I am doing in the guide "Learn Python The Hard Way" seems repetitive. Does my code for each time it uses the function with open in it, open it? it just seems repetitive.

You think it would maybe just keep the file opened so that way you don't have to open it that much? another way i'm thinking of how it works is when a function like write() needs to access the file, instead of opening the file like i think it is each time it just uses the filename variable inside the open function instead of using the open() function to open it each time.

The target variable has the value of: open(filename, 'w') and we pass the name of the file to filename using argv upon executing the script.

I'm new to python, here is the pastebin link:

Join the Next Reality AR Community

Get the latest in AR — delivered straight to your inbox.

3 Responses

"keep the file opened so that way you don't have to open it that much"

Take a look at the with open statement.

Here is a pastbin copy of your code using the with open statement.

Let me know if you have any questions.

I can't see your pastebin links right now, but it sounds like the with statement is probably the way to go. I think it's also worth saying though, that once you have opened a file, with ex: f = open('somefile', 'w') or whatever.. then that file is accessible through f (f stays open) until you do f.close() or perhaps end the program. So you shouldn't need to keep opening a file to use it unless you closed it beforehand or used the with statement. Sorry if that's not what you were saying.

I've got it, so I think. I have spent a good amount of time over various examples on the with statement.

with open(filename) as file:
print "done"

File is the variable which the "file object" is stored in, and is used to reference the "file object", Which is allowing us to act on the file itself using one of the modes in open().

"with" is saying open the file, with the open function, using the "filename" parameter to get the "filename" value (name of file), and store the file object in the variable "file" which is referenced in the actions we decide to do in the code block following the "with" statement.

This is pretty hard to understand for me at this point, but thank you for mentioning it as it will make code more clean in the future. I think for now I wont stray to far from this tutorial so I don't get stuck on one particular thing for too long.

Share Your Thoughts

  • Hot
  • Active