-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path2021-03-06_Writing-Files-Using-Python-d46b4851366f.html
More file actions
217 lines (214 loc) · 18.7 KB
/
Copy path2021-03-06_Writing-Files-Using-Python-d46b4851366f.html
File metadata and controls
217 lines (214 loc) · 18.7 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Writing Files Using Python</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<article class="h-entry">
<header>
<h1 class="p-name">Writing Files Using Python</h1>
</header>
<section data-field="subtitle" class="p-summary">
Basics of Writing Files in Python
The common methods to operate with files are open() to open a file,
</section>
<section data-field="body" class="e-content">
<section name="dbc5" class="section section--body section--first section--last">
<div class="section-divider">
<hr class="section-divider">
</div>
<div class="section-content">
<div class="section-inner sectionLayout--insetColumn">
<h3 name="874f" id="874f" class="graf graf--h3 graf--leading graf--title">Writing Files Using Python</h3>
<p name="5ad7" id="5ad7" class="graf graf--p graf-after--h3">Basics of Writing Files in Python<br>The
common methods to operate with files are open() to open a file,</p>
<p name="556c" id="556c" class="graf graf--p graf-after--p">seek() to set the file’s current position at
the given offset, and</p>
<p name="62e1" id="62e1" class="graf graf--p graf-after--p">close() to close th</p>
<p name="e6a7" id="e6a7" class="graf graf--p graf-after--p">As pointed out in a previous article that
deals with reading data from files, file handling belongs to the essential knowledge of every
professional Python programmer. This feature is a core part of the Python language, and no extra module
needs to be loaded to do it properly.</p>
<h3 name="1d2b" id="1d2b" class="graf graf--h3 graf-after--p">Basics of Writing Files in Python</h3>
<p name="5b5f" id="5b5f" class="graf graf--p graf-after--h3">The common methods to operate with files are
<code class="markup--code markup--p-code">open()</code> to open a file, <code
class="markup--code markup--p-code">seek()</code> to set the file's current position at the given
offset, and <code class="markup--code markup--p-code">close()</code> to close the file afterwards. The
<code class="markup--code markup--p-code">open()</code> method returns a file handle that represents a
<a href="https://docs.python.org/3/glossary.html#term-file-object"
data-href="https://docs.python.org/3/glossary.html#term-file-object"
class="markup--anchor markup--p-anchor" rel="noopener" target="_blank">file object</a> to be used to
access the file for reading, writing, or appending.</p>
<p name="f6bb" id="f6bb" class="graf graf--p graf-after--p">Writing to a file requires a few
decisions — the name of the file in which to store data and the access mode of the file. Available are
two modes, writing to a new file (and overwriting any existing data) and appending data at the end of a
file that already exists. The according abbreviations are “w”, and “a”, and have to be specified before
opening a file.</p>
<p name="a4b1" id="a4b1" class="graf graf--p graf-after--p">In this article we will explain how to write
data to a file line by line, as a list of lines, and appending data at the end of a file.</p>
<h3 name="037c" id="037c" class="graf graf--h3 graf-after--p">Writing a Single Line to a File</h3>
<p name="1cc9" id="1cc9" class="graf graf--p graf-after--h3">This first example is pretty similar to
writing to files with the popular programming languages C and C++, as you’ll see in <em
class="markup--em markup--p-em">Listing 1</em>. The process is pretty straightforward. First, we open
the file using the <code class="markup--code markup--p-code">open()</code> method for writing, write a
single line of text to the file using the <code class="markup--code markup--p-code">write()</code>
method, and then close the file using the <code class="markup--code markup--p-code">close()</code>
method. Keep in mind that due to the way we opened the "helloworld.txt" file it will either be
created if it does not exist yet, or it will be completely overwritten.</p>
<pre name="c054" id="c054"
class="graf graf--pre graf-after--p">filehandle = open('helloworld.txt', 'w')<br>filehandle.write('Hello, world!\n')<br>filehandle.close()</pre>
<p name="af09" id="af09" class="graf graf--p graf-after--pre"><em class="markup--em markup--p-em">Listing
1</em></p>
<p name="1fc2" id="1fc2" class="graf graf--p graf-after--p">This entire process can be shortened using the
<code class="markup--code markup--p-code">with</code> statement. <em
class="markup--em markup--p-em">Listing 2</em> shows how to write that. As already said before keep in
mind that by opening the "helloworld.txt" file this way will either create if it does not
exist yet or completely overwritten, otherwise.</p>
<pre name="7cea" id="7cea"
class="graf graf--pre graf-after--p">with open('helloworld.txt', 'w') as filehandle:<br> filehandle.write('Hello, world!\n')</pre>
<p name="84b9" id="84b9" class="graf graf--p graf-after--pre"><em class="markup--em markup--p-em">Listing
2</em></p>
<h3 name="7ded" id="7ded" class="graf graf--h3 graf-after--p">Writing a List of Lines to a File</h3>
<p name="5123" id="5123" class="graf graf--p graf-after--h3">In reality a file does not consist only of a
single line, but much more data. Therefore, the contents of the file are stored in a list that
represents a file buffer. To write the entire file buffer we’ll use the <code
class="markup--code markup--p-code">writelines()</code> method. <em
class="markup--em markup--p-em">Listing 3</em> gives you an example of this.</p>
<pre name="5995" id="5995"
class="graf graf--pre graf-after--p">filehandle = open("helloworld.txt", "w")<br>filebuffer = ["a first line of text", "a second line of text", "a third line"]<br>filehandle.writelines(filebuffer)<br>filehandle.close()</pre>
<p name="dcb7" id="dcb7" class="graf graf--p graf-after--pre"><em class="markup--em markup--p-em">Listing
3</em></p>
<p name="a0b0" id="a0b0" class="graf graf--p graf-after--p">Running the Python program shown in <em
class="markup--em markup--p-em">Listing 3</em> and then using the <code
class="markup--code markup--p-code">cat</code> command we can see that the file
"helloworld.txt" has the following content:</p>
<pre name="9ad6" id="9ad6"
class="graf graf--pre graf-after--p">$ cat helloworld.txt<br>a first line of text a second line of text a third line</pre>
<p name="d205" id="d205" class="graf graf--p graf-after--pre"><em class="markup--em markup--p-em">Listing
4</em></p>
<p name="5dc8" id="5dc8" class="graf graf--p graf-after--p">This happens because <strong
class="markup--strong markup--p-strong">the </strong><code class="markup--code markup--p-code"><strong
class="markup--strong markup--p-strong">writelines()</strong></code><strong
class="markup--strong markup--p-strong"> method does not automatically add any line separators when
writing the data</strong>. <em class="markup--em markup--p-em">Listing 5</em> shows how to achieve
that, writing each line of text on a single line by adding the line separator "\n". Using a
generator expression each line is substituted by the line plus line separator. Again, you can formulate
this using the <code class="markup--code markup--p-code">with</code> statement.</p>
<pre name="968e" id="968e"
class="graf graf--pre graf-after--p">with open('helloworld.txt', 'w') as filehandle:<br> filebuffer = ["a line of text", "another line of text", "a third line"]<br> filehandle.writelines("%s\n" % line for line in filebuffer)</pre>
<p name="670b" id="670b" class="graf graf--p graf-after--pre"><em class="markup--em markup--p-em">Listing
5</em></p>
<p name="07bd" id="07bd" class="graf graf--p graf-after--p">Now, the output file “helloworld.txt” has the
desired content as shown in <em class="markup--em markup--p-em">Listing 6</em>:</p>
<pre name="8f69" id="8f69"
class="graf graf--pre graf-after--p">$ cat helloworld.txt<br>a first line of text<br>a second line of text<br>a third line</pre>
<p name="2afe" id="2afe" class="graf graf--p graf-after--pre"><em class="markup--em markup--p-em">Listing
6</em></p>
<p name="bf0a" id="bf0a" class="graf graf--p graf-after--p">Interestingly, there is a way to use output
redirection in Python to write data to files. <em class="markup--em markup--p-em">Listing 7</em> shows
how to code that for Python 2.x.</p>
<pre name="5db0" id="5db0"
class="graf graf--pre graf-after--p">filename = "helloworld.txt"<br><br></pre>
<pre name="4917" id="4917"
class="graf graf--pre graf-after--pre">filecontent = ["Hello, world", "a second line", "and a third line"]</pre>
<pre name="a9d1" id="a9d1"
class="graf graf--pre graf-after--pre">with open(filename, 'w') as filehandle:<br> <br> for line in filecontent:<br> print >>filehandle, line</pre>
<p name="a955" id="a955" class="graf graf--p graf-after--pre"><em class="markup--em markup--p-em">Listing
7</em></p>
<p name="0d81" id="0d81" class="graf graf--p graf-after--p">For the latest Python releases this does not
work in the same way anymore. To do something like this we must use the <code
class="markup--code markup--p-code"><strong
class="markup--strong markup--p-strong">sys</strong></code> module. It allows us to access the UNIX
standard output channels via <code class="markup--code markup--p-code">sys.stdout</code>, <code
class="markup--code markup--p-code">sys.stdin</code>, and <code
class="markup--code markup--p-code">sys.stderr</code>.</p>
<p name="24e0" id="24e0" class="graf graf--p graf-after--p">In our case we preserve the original value of
the output channel <code class="markup--code markup--p-code">sys.stdout</code>, first (line 8 in the
code below), redefine it to the handle of our output file,</p>
<p name="1313" id="1313" class="graf graf--p graf-after--p">next (line 15), print the data as usual (line
18), and finally restore the original value of the output channel <code
class="markup--code markup--p-code">sys.stdout</code> (line 21). <em
class="markup--em markup--p-em">Listing 8</em> contains the example code.</p>
<pre name="fdbc" id="fdbc" class="graf graf--pre graf-after--p">import sys<br><br></pre>
<pre name="6ca4" id="6ca4"
class="graf graf--pre graf-after--pre">filename = "helloworld.txt"<br><br></pre>
<pre name="cca3" id="cca3" class="graf graf--pre graf-after--pre">original = sys.stdout<br><br></pre>
<pre name="319f" id="319f"
class="graf graf--pre graf-after--pre">filecontent = ["Hello, world", "a second line", "and a third line"]</pre>
<pre name="c99f" id="c99f"
class="graf graf--pre graf-after--pre">with open(filename, 'w') as filehandle:<br> <br> sys.stdout = filehandle<br> <br> for line in filecontent:<br> print(line)<br> <br> <br> sys.stdout = original</pre>
<p name="8ee1" id="8ee1" class="graf graf--p graf-after--pre"><em class="markup--em markup--p-em">Listing
8</em></p>
<p name="dd9d" id="dd9d" class="graf graf--p graf-after--p">This is not necessarily best practice, but it
does give you other options for writing lines to a file.</p>
<h3 name="cb84" id="cb84" class="graf graf--h3 graf-after--p">Appending Data to a File</h3>
<p name="e29e" id="e29e" class="graf graf--p graf-after--h3">So far, we have stored data in new files or
in overwritten data in existing files. But what if we want to append data to the end of an existing
file? In this case we would need to open the existing file using a different access mode. We change that
to ‘a’ instead of ‘w’.</p>
<p name="4063" id="4063" class="graf graf--p graf-after--p"><em class="markup--em markup--p-em">Listing
9</em> shows how to handle that. And <em class="markup--em markup--p-em">Listing 10</em> does the same
thing, but it uses the <code class="markup--code markup--p-code">with</code> statement rather.</p>
<pre name="86b2" id="86b2"
class="graf graf--pre graf-after--p">filehandle = open('helloworld.txt','a')<br>filehandle.write('\n' + 'Hello, world!\n')<br>filehandle.close()</pre>
<p name="468d" id="468d" class="graf graf--p graf-after--pre"><em class="markup--em markup--p-em">Listing
9</em></p>
<pre name="9096" id="9096"
class="graf graf--pre graf-after--p">with open('helloworld.txt', 'a') as filehandle:<br> filehandle.write('\n' + 'Hello, world!\n')</pre>
<p name="926c" id="926c" class="graf graf--p graf-after--pre"><em class="markup--em markup--p-em">Listing
10</em></p>
<p name="0817" id="0817" class="graf graf--p graf-after--p">Using the same helloworld.txt file from
before, running this code will produce the following file contents:</p>
<pre name="e827" id="e827"
class="graf graf--pre graf-after--p">$ cat helloworld.txt<br>Hello, world<br>a second line<br>and a third line</pre>
<pre name="16d9" id="16d9" class="graf graf--pre graf-after--pre">Hello, world!</pre>
<h3 name="8194" id="8194" class="graf graf--h3 graf-after--pre">Conclusion</h3>
<p name="ba8a" id="ba8a" class="graf graf--p graf-after--h3">Writing plain text data to files, or
appending data to existing files, is as easy as reading from files in Python. As soon as a file is
closed after writing or appending data, Python triggers a synchronization call. As a result, the updated
file is immediately written to disk.</p>
<h4 name="e63e" id="e63e" class="graf graf--h4 graf-after--p">If you found this guide helpful feel free to
checkout my github/gists where I host similar content:</h4>
<p name="1c2f" id="1c2f" class="graf graf--p graf-after--h4"><a href="https://gist.github.com/bgoonz"
data-href="https://gist.github.com/bgoonz" class="markup--anchor markup--p-anchor" rel="noopener"
target="_blank">bgoonz’s gists · GitHub</a></p>
<div name="3585" id="3585" class="graf graf--mixtapeEmbed graf-after--p"><a
href="https://github.com/bgoonz" data-href="https://github.com/bgoonz"
class="markup--anchor markup--mixtapeEmbed-anchor" title="https://github.com/bgoonz"><strong
class="markup--strong markup--mixtapeEmbed-strong">bgoonz — Overview</strong><br><em
class="markup--em markup--mixtapeEmbed-em">Web Developer, Electrical Engineer JavaScript | CSS |
Bootstrap | Python | React | Node.js | Express | Sequelize…</em>github.com</a><a
href="https://github.com/bgoonz" class="js-mixtapeImage mixtapeImage u-ignoreBlock"
data-media-id="6ee74d5200d495ddc7ddad0c92bd6dce" data-thumbnail-img-id="0*Udg3rbeFyslZ9dyl"
style="background-image: url(https://cdn-images-1.medium.com/fit/c/160/160/0*Udg3rbeFyslZ9dyl);"></a>
</div>
<p name="cb1a" id="cb1a" class="graf graf--p graf-after--mixtapeEmbed">Or Checkout my personal Resource
Site:</p>
<div name="4bce" id="4bce" class="graf graf--mixtapeEmbed graf-after--p graf--trailing"><a
href="https://goofy-euclid-1cd736.netlify.app/" data-href="https://goofy-euclid-1cd736.netlify.app/"
class="markup--anchor markup--mixtapeEmbed-anchor"
title="https://goofy-euclid-1cd736.netlify.app/"><strong
class="markup--strong markup--mixtapeEmbed-strong">a/A-Student-Resources</strong><br><em
class="markup--em markup--mixtapeEmbed-em">Edit
description</em>goofy-euclid-1cd736.netlify.app</a><a
href="https://goofy-euclid-1cd736.netlify.app/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"
data-media-id="260adefce95974b3b8f27566d0434b9c" data-thumbnail-img-id="0*kHvsYWw7LFYl0PB_"
style="background-image: url(https://cdn-images-1.medium.com/fit/c/160/160/0*kHvsYWw7LFYl0PB_);"></a>
</div>
</div>
</div>
</section>
</section>
<footer>
<p>By <a href="https://medium.com/@bryanguner" class="p-author h-card">Bryan Guner</a> on <a
href="https://medium.com/p/d46b4851366f"><time class="dt-published"
datetime="2021-03-06T11:41:18.786Z">March 6, 2021</time></a>.</p>
<p><a href="https://medium.com/@bryanguner/writing-files-using-python-d46b4851366f"
class="p-canonical">Canonical link</a></p>
<p>Exported from <a href="https://medium.com">Medium</a> on April 3, 2021.</p>
</footer>
</article>
</body>
</html>