-
Notifications
You must be signed in to change notification settings - Fork 0
/
chapter_2.html
77 lines (62 loc) · 3.08 KB
/
chapter_2.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
Chapter 2. Python - File Open
<div class="container">
<div class="divider"></div>
<P>File handling is an important part of any web application.
Python has several functions for creating, reading, updating, and deleting files.</P>
<H5>File Handling</H5>
<p>The key function for working with files in Python is the open() function.<br>
The open() function takes two parameters; filename, and mode.<br>
There are four different methods (modes) for opening a file:</p>
<div class="row">
<div class="card-panel grey lighten-5 z-depth-1">
<div class="row valign-wrapper">
<div class="col s12">
<p>"r" - Read - Default value. Opens a file for reading, error if the file does not exist <br>
"a" - Append - Opens a file for appending, creates the file if it does not exist <br>
"w" - Write - Opens a file for writing, creates the file if it does not exist <br>
"x" - Create - Creates the specified file, returns an error if the file exists</p>
</div>
</div>
</div>
</div>
<p>In addition you can specify if the file should be handled as binary or text mode</p>
<div class="row">
<div class="card-panel grey lighten-5 z-depth-1">
<div class="row valign-wrapper">
<div class="col s12">
<p>"t" - Text - Default value. Text mode <br>
"b" - Binary - Binary mode (e.g. images)</p>
</div>
</div>
</div>
</div>
<div class="divider"></div>
<h5>Syntax</h5>
<p>To open a file for reading it is enough to specify the name of the file:</p>
<div class="row">
<div class="card-panel grey lighten-5 z-depth-1">
<div class="row valign-wrapper">
<div class="col s12">
<p>f = open("demofile.txt")</p>
</div>
</div>
</div>
</div>
<p>The code above is the same as:</p>
<div class="row">
<div class="card-panel grey lighten-5 z-depth-1">
<div class="row valign-wrapper">
<div class="col s12">
<p>f = open("demofile.txt", "rt")</p>
</div>
</div>
</div>
</div>
<p>Because "r" for read, and "t" for text are the default values, you do not need to specify them.<br>
<b>Note:</b> Make sure the file exists, or else you will get an error.</p>
<div class="divider"></div>
<div class="row"></div>
<div class="video-container">
<iframe width="560" height="315" src="https://www.youtube.com/embed/Uh2ebFW8OYM" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
</div>