The 'with' and 'as' Keywords. What is the variable?


#1

This lesson does a really bad job of explaining the syntax. What is the “variable” in the below…



with open("file", "mode") as variable:



#2

That line creates a variable named variable


#3

A variable for what?


#4

It’ll refer to whatever the context manager provides. Some resource. In this case, a file object.

You could also write that as:

variable = open('file', 'mode')

# ...

variable.close()

#5

so in this example:

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

If text.txt is my text file, I am thinking a big file. Then within that file, there is an object called “my_file” that I am writing to?


#6

text.txt is a filename

And objects aren’t obtained from within the file, unless you specifically start executing it somehow

The size plays no part in that code

open provides a file object which my_file is assigned to

values and objects are the same thing in python, so file object means “a value with an interface to a file on the os”


#7

Man maybe I am not asking my questions clear enough to you.

If I wanted to just write “My Data” to the file, which is specified as “Text.txt”, then what is the point of now making an object called my_file. I thought the “file” was “text.txt”

This would make sense - obviously its not correct.

with open("text.txt", "w"):
  text.text.write("My Data!")


#8

You’re getting the jargon wrong, can’t communicate before having agreed on what things mean or what one person says will not match what the other hears.

objects don’t have names. You can create variables which refer to objects. That’s as close as you’ll get.

You will need to open a file to write to it. How would you write to something that you can’t reference?


#9

Ok - sorry for the confusion, this lesson is a bit confusing and doesn’t do much explaining.

Let’s see if ich verstehen.

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

with open(“text.txt”, “w”) - this opens the file “text.txt” and “w” puts the file in a mode to be written to.

as my_file: - my file is a variable, which is basically a variable that acts as a reference to my “text.txt” file.

my_file.write(“My Data!”) - my_file continues to act as the reference to “text.txt” and the .write(“My Data”) writes “My Data” to the “text.txt” file.


#10

yes, my_file will refer to a file object, and that object in turn knows how to talk with the os

methods of that file object, like write, are part of that interface. So when you call write, that object will do the things necessary to get that data to eventually end up on the disk.

And the os in turn will do a bunch of voodoo. For example it won’t immediately write to disk, it’ll stay in ram while the file is hot.


#11

Got it - thanks for your help.


#12

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