+ 1

Python and "with" statement

I have recently seen a "with" statement used like so: with open("file.txt","r") as f: f.read() As much as i understand it... this shortcuts come part of method or variable. So in my thinking way this should work: list = [1,2,3] with list as l: print(l[1]) But it gives me error... So what is "with" statement used for?

11th Aug 2017, 5:56 PM
Paweł Karaś
Paweł Karaś - avatar
4 Antworten
+ 2
with - specifically for OS BIOS it is used opening files with open('txt.js','r') as f: # with helps name the file to a variable f lines = f.readlines () if lines == None: pass else: print(lines)
11th Aug 2017, 6:06 PM
Given
Given - avatar
+ 2
and calling a variable list is forbidden as it is a reserved word :)
11th Aug 2017, 9:53 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 1
So i'm unable to get variables or methods like that but in shorter form?
11th Aug 2017, 6:14 PM
Paweł Karaś
Paweł Karaś - avatar
+ 1
Thanks :)
12th Aug 2017, 5:28 AM
Paweł Karaś
Paweł Karaś - avatar