Skip to content

Commit 581da4c

Browse files
committed
Added With_As.md
1 parent f3a0495 commit 581da4c

File tree

3 files changed

+35
-0
lines changed

3 files changed

+35
-0
lines changed

WA1.png

13.8 KB
Loading

WA2.png

9.17 KB
Loading

With_As.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
## With As
2+
```python
3+
With the "With" statement, you get better syntax and exceptions handling. The with statement simplifies exception handling by encapsulating common preparation and cleanup tasks.In addition, it will automatically close the file. The with statement provides a way for ensuring that a clean-up is always used.The lines after as can be used as an object to refer that.Without the with statement, we would write something like this:
4+
5+
file = open("hello.txt")
6+
data = file.read()
7+
print data
8+
file.close() # It's important to close the file when you're done with it
9+
10+
With Statement Usage
11+
Opening a file using with is as simple as:
12+
13+
with open(filename) as file:
14+
with open("hello.txt") as inFile: # Use file to refer to the file object
15+
data = inFile.read()
16+
print data
17+
18+
Here we did not write separate close statement as it is handled by with.
19+
```
20+
![Output](/WA1.png)
21+
Above is the file hello.txt
22+
![Code](/WA2.png)
23+
```python
24+
Thus we can see that when we use “with” statement there is no need of separate close statement.
25+
With more than one item, the context managers are processed as if multiple with statements were nested:
26+
with A() as a, B() as b:
27+
suite
28+
is equivalent to
29+
with A() as a:
30+
with B() as b:
31+
suite
32+
```
33+
34+
35+

0 commit comments

Comments
 (0)