{"id":6106,"date":"2022-05-20T16:55:14","date_gmt":"2022-05-20T14:55:14","guid":{"rendered":"http:\/\/miro.borodziuk.eu\/?p=6106"},"modified":"2026-01-22T23:46:02","modified_gmt":"2026-01-22T22:46:02","slug":"file-processing-in-python","status":"publish","type":"post","link":"http:\/\/miro.borodziuk.eu\/index.php\/2022\/05\/20\/file-processing-in-python\/","title":{"rendered":"File processing in Python"},"content":{"rendered":"<p>Due to the type of the stream&#8217;s contents, <strong>all the streams are divided into text and binary streams<\/strong>. The text streams ones are structured in lines; that is, they contain typographical characters (letters, digits, punctuation, etc.) arranged in rows (lines), as seen with the naked eye when you look at the contents of the file in the editor. This file is written (or read) mostly character by character, or line by line.<\/p>\n<p><!--more--><\/p>\n<p>The binary streams don&#8217;t contain text but a sequence of bytes of any value. This sequence can be, for example, an executable program, an image, an audio or a video clip, a database file, etc.<\/p>\n<p>Because these files don&#8217;t contain lines, the reads and writes relate to portions of data of any size. Hence the data is read\/written byte by byte, or block by block, where the size of the block usually ranges from one to an arbitrarily chosen value.<\/p>\n<p>&nbsp;<\/p>\n<p>1. A file needs to be <b>open<\/b> before it can be processed by a program, and it should be <b>closed<\/b> when the processing is finished.<\/p>\n<p>Opening the file associates it with the <b>stream<\/b>, which is an abstract representation of the physical data stored on the media. The way in which the stream is processed is called <b>open mode<\/b>. <b>Three<\/b> open modes exist:<\/p>\n<ul>\n<li><b>read mode<\/b> \u2013 only read operations are allowed; trying to write to the stream will cause an exception (the exception is named <strong><span style=\"font-family: Courier New;\">UnsupportedOperation<\/span><\/strong>, which inherits <strong><span style=\"font-family: Courier New;\">OSError<\/span> <\/strong>and <strong><span style=\"font-family: Courier New;\">ValueError<\/span><\/strong>, and comes from the <span style=\"font-family: Courier New;\">io<\/span> module);<\/li>\n<li><b>write mode<\/b> \u2013 only write operations are allowed; attempting to read the stream will cause the exception mentioned above;<\/li>\n<li><b>update mode<\/b> \u2013 both writes and reads are allowed.<\/li>\n<\/ul>\n<p>&nbsp;<\/p>\n<p>2. Depending on the physical file content, different Python classes can be used to process files. In general, the <code>BufferedIOBase<\/code> is able to process any file, while <code>TextIOBase<\/code> is a specialized class dedicated to processing text files (i.e. files containing human-visible texts divided into lines using new-line markers). Thus, the streams can be divided into <b>binary<\/b> and <b>text<\/b> ones.<\/p>\n<p>The text streams ones are structured in lines; that is, they contain typographical characters (letters, digits, punctuation, etc.) arranged in rows (lines), as seen with the naked eye when you look at the contents of the file in the editor.<\/p>\n<p>The binary streams don&#8217;t contain text but a sequence of bytes of any value. This sequence can be, for example, an executable program, an image, an audio or a video clip, a database file, etc.<\/p>\n<p>&nbsp;<\/p>\n<p>3. The following <code><strong>open()<\/strong><\/code> function syntax is used to open a file:<\/p>\n<pre class=\"lang:default decode:true\">open(file_name, mode=open_mode, encoding=text_encoding)<\/pre>\n<p>The invocation creates a stream object and associates it with the file named <code>file_name<\/code>, using the specified <code>open_mode<\/code> and setting the specified <code>text_encoding<\/code>, or it <b>raises an exception in the case of an error<\/b>.<\/p>\n<p>Example:<\/p>\n<pre class=\"lang:default decode:true\">try:\r\n    stream = open(\"C:\\Users\\User\\Desktop\\file.txt\", \"rt\")\r\n    # Processing goes here.\r\n    stream.close()\r\nexcept Exception as exc:\r\n    print(\"Cannot open the file:\", exc)\r\n\r\n<\/pre>\n<p>If the opening is successful, the function returns a stream object; otherwise, an exception is raised (e.g., <strong><span style=\"font-family: Courier New;\">FileNotFoundError<\/span> <\/strong>if the file you&#8217;re going to read doesn&#8217;t exist);<\/p>\n<p>Note: the mode and encoding arguments may be omitted &#8211; their default values are assumed then. The default opening mode is reading in text mode, while the default encoding depends on the platform used. As <strong>text is the default setting<\/strong>, we can skip the <strong><code>t<\/code> <\/strong>in mode string.<\/p>\n<h2>Opening the streams: modes<\/h2>\n<p><code><strong>r<\/strong><\/code> open mode: read<\/p>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul>\n<li>the stream will be opened in <strong>read mode<\/strong>;<\/li>\n<li>the file associated with the stream <strong>must exist<\/strong> and has to be readable, otherwise the <code>open()<\/code> function raises an exception.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<p><code><strong>w<\/strong><\/code> open mode: write<\/p>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul>\n<li>the stream will be opened in <strong>write mode<\/strong>;<\/li>\n<li>the file associated with the stream <strong>doesn&#8217;t need to exist<\/strong>; if it doesn&#8217;t exist it will be created; if it exists, it will be truncated to the length of zero (erased); if the creation isn&#8217;t possible (e.g., due to system permissions) the <code>open()<\/code> function raises an exception.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<p><code><strong>a<\/strong><\/code> open mode: append<\/p>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul>\n<li>the stream will be opened in <strong>append mode<\/strong>;<\/li>\n<li>the file associated with the stream <strong>doesn&#8217;t need to exist<\/strong>; if it doesn&#8217;t exist, it will be created; if it exists the virtual recording head will be set at the end of the file (the previous content of the file remains untouched.)<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<p><code><strong>r+<\/strong><\/code> open mode: read and update<\/p>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul>\n<li>the stream will be opened in <strong>read and update mode<\/strong>;<\/li>\n<li>the file associated with the stream <strong>must exist and has to be writeable<\/strong>, otherwise the <code>open()<\/code> function raises an exception;<\/li>\n<li>both read and write operations are allowed for the stream.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<p><code><strong>w+<\/strong><\/code> open mode: write and update<\/p>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul>\n<li>the stream will be opened in <strong>write and update<\/strong> mode;<\/li>\n<li>the file associated with the stream <strong>doesn&#8217;t need to exist<\/strong>; if it doesn&#8217;t exist, it will be created; the previous content of the file remains untouched;<\/li>\n<li>both read and write operations are allowed for the stream.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<h2>Selecting text and binary modes<\/h2>\n<p>If there is a letter <code><strong>b<\/strong><\/code> at the end of the mode string it means that the stream is to be opened in the <strong>binary mode<\/strong>.<\/p>\n<p>If the mode string ends with a letter <code><strong>t<\/strong><\/code> the stream is opened in the <strong>text mode<\/strong>.<\/p>\n<p>Text mode is the default behaviour assumed when no binary\/text mode specifier is used.<\/p>\n<p>Finally, the successful opening of the file will set the current file position (the virtual reading\/writing head) before the first byte of the file <strong>if the mode is not <code>a<\/code><\/strong> and after the last byte of file <strong>if the mode is set to <code>a<\/code><\/strong>.<\/p>\n<p>&nbsp;<\/p>\n<table>\n<thead>\n<tr>\n<th>Text mode<\/th>\n<th>Binary mode<\/th>\n<th>Description<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td><code>rt<\/code><\/td>\n<td><code>rb<\/code><\/td>\n<td>read<\/td>\n<\/tr>\n<tr>\n<td><code>wt<\/code><\/td>\n<td><code>wb<\/code><\/td>\n<td>write<\/td>\n<\/tr>\n<tr>\n<td><code>at<\/code><\/td>\n<td><code>ab<\/code><\/td>\n<td>append<\/td>\n<\/tr>\n<tr>\n<td><code>r+t<\/code><\/td>\n<td><code>r+b<\/code><\/td>\n<td>read and update<\/td>\n<\/tr>\n<tr>\n<td><code>w+t<\/code><\/td>\n<td><code>w+b<\/code><\/td>\n<td>write and update<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>&nbsp;<\/p>\n<p><strong><span class=\"label\">EXTRA<\/span><\/strong><\/p>\n<p>You can also open a file for its exclusive creation. You can do this using the <strong><code>x<\/code> <\/strong>open mode. If the file already exists, the <code>open()<\/code> function will raise an exception.<\/p>\n<p>&nbsp;<\/p>\n<p><strong>Closing streams<\/strong><\/p>\n<p>The last operation performed on a stream (this doesn&#8217;t include the stdin, stdout, and stderr streams which don&#8217;t require it) should be <strong>closing<\/strong>.<\/p>\n<p>That action is performed by a method invoked from within open stream object: <code><strong>stream.close()<\/strong><\/code>.<\/p>\n<p>&nbsp;<\/p>\n<p>4. Three <b>predefined<\/b> streams are already open when the program starts:<\/p>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul>\n<li><code><strong>sys.stdin<\/strong><\/code>\u00a0(as <i>standard input<\/i>)\n<ul>\n<li>the <code>stdin<\/code> stream is normally associated with the keyboard, pre-open for reading and regarded as the primary data source for the running programs;<\/li>\n<li>the well-known <code>input()<\/code> function reads data from <code>stdin<\/code> by default.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul>\n<li><strong><code>sys.stdout<\/code><\/strong>\u00a0(as <i>standard output<\/i>)\n<ul>\n<li>the <code>stdout<\/code> stream is normally associated with the screen, pre-open for writing, regarded as the primary target for outputting data by the running program;<\/li>\n<li>the well-known <code>print()<\/code> function outputs the data to the <code>stdout<\/code> stream.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul>\n<li><code><strong>sys.stderr<\/strong><\/code> (as <i>standard error output<\/i>)\n<ul>\n<li>the <code>stderr<\/code> stream is normally associated with the screen, pre-open for writing, regarded as the primary place where the running program should send information on the errors encountered during its work;<\/li>\n<li>the separation of <code>stdout<\/code> (useful results produced by the program) from the <code>stderr<\/code> (error messages, undeniably useful but does not provide results) gives the possibility of redirecting these two types of information to the different targets.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<p>When our program starts, the three streams are already opened and don&#8217;t require any extra preparations. What&#8217;s more, your program can use these streams explicitly if you take care to import the <code><strong>sys<\/strong><\/code> module:<\/p>\n<div class=\"ace-tm\">\n<div class=\"ace_static_highlight\">\n<div class=\"ace_line\">\n<pre class=\"lang:default decode:true\">import sys<\/pre>\n<p>&nbsp;<\/p>\n<\/div>\n<div class=\"ace_line\"><\/div>\n<\/div>\n<\/div>\n<p>5. The <strong><code>IOError<\/code> <\/strong>object is equipped with a property named <strong><code>errno<\/code> \u00a0<\/strong>and you can access it as follows:<\/p>\n<pre class=\"lang:default decode:true \">try:\r\n    # Some stream operations.\r\nexcept IOError as exc:\r\n    print(exc.errno)\r\n\r\n<\/pre>\n<div class=\"small-12 large-6 columns\">\n<p>The value of the <code>errno<\/code> attribute can be compared with one of the predefined symbolic constants defined in the <code>errno<\/code> module.<\/p>\n<\/div>\n<div class=\"small-12 large-6 columns\">\n<p>Let&#8217;s take a look at some selected <strong>constants useful for detecting stream errors<\/strong>:<\/p>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul>\n<li><strong><code>errno.EACCES<\/code><\/strong> \u2192 <span style=\"font-family: Courier New;\">Permission denied <\/span>The error occurs when you try, for example, to open a file with the <i>read only<\/i> attribute for writing.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul>\n<li><code><strong>errno.EBADF<\/strong><\/code> \u2192 <span style=\"font-family: Courier New;\">Bad file number <\/span>The error occurs when you try, for example, to operate with an unopened stream.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul>\n<li><code><strong>errno.EEXIST<\/strong><\/code> \u2192 <span style=\"font-family: Courier New;\">File exists <\/span>The error occurs when you try, for example, to rename a file with its previous name.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul>\n<li><code><strong>errno.EFBIG<\/strong><\/code> \u2192 <span style=\"font-family: Courier New;\">File too large <\/span>The error occurs when you try to create a file that is larger than the maximum allowed by the operating system.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul>\n<li><code><strong>errno.EISDIR<\/strong><\/code> \u2192 <span style=\"font-family: Courier New;\">Is a directory <\/span>The error occurs when you try to treat a directory name as the name of an ordinary file.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul>\n<li><code><strong>errno.EMFILE<\/strong><\/code> \u2192 <span style=\"font-family: Courier New;\">Too many open files <\/span>The error occurs when you try to simultaneously open more streams than acceptable for your operating system.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul>\n<li><code><strong>errno.ENOENT<\/strong><\/code> \u2192 <span style=\"font-family: Courier New;\">No such file or directory <\/span>The error occurs when you try to access a non-existent file\/directory.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul>\n<li><code><strong>errno.ENOSPC<\/strong><\/code> \u2192 <span style=\"font-family: Courier New;\">No space left on device<\/span> The error occurs when there is no free space on the media.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<p>The complete list is much longer (it includes also some error codes not related to the stream processing.)<\/p>\n<\/div>\n<p>Example:<\/p>\n<pre class=\"lang:default decode:true \">import errno\r\n\r\ntry:\r\n    s = open(\"c:\/users\/user\/Desktop\/file.txt\", \"rt\")\r\n    # Actual processing goes here.\r\n    s.close()\r\nexcept Exception as exc:\r\n    if exc.errno == errno.ENOENT:\r\n        print(\"The file doesn't exist.\")\r\n    elif exc.errno == errno.EMFILE:\r\n        print(\"You've opened too many files.\")\r\n    else:\r\n        print(\"The error number is:\", exc.errno)<\/pre>\n<p>&nbsp;<\/p>\n<p>6. There is a function that can dramatically simplify the error handling code. Its name is <strong><code>strerror()<\/code><\/strong>, and it comes from the <code>os<\/code> module and <strong>expects just one argument &#8211; an error number<\/strong>.<\/p>\n<p>Its role is simple: you give an error number and get a string describing the meaning of the error.<\/p>\n<p>Note: if you pass a non-existent error code (a number which is not bound to any actual error), the function will raise <strong><span style=\"font-family: Courier New;\">ValueError<\/span> <\/strong>exception.<\/p>\n<pre class=\"lang:default decode:true\">from os import strerror\r\n\r\ntry:\r\n    s = open(\"c:\/users\/user\/Desktop\/file.txt\", \"rt\")\r\n    # Actual processing goes here.\r\n    s.close()\r\nexcept Exception as exc:\r\n    print(\"The file could not be opened:\", strerror(exc.errno))\r\n\r\n<\/pre>\n<p>&nbsp;<\/p>\n<p>7. To read a file\u2019s contents, the following stream methods can be used:<\/p>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul>\n<li><code><strong>read(number)<\/strong><\/code> \u2013 reads the <code>number<\/code> characters\/bytes from the file and returns them as a string; is able to read the whole file at once;If applied to a text file, the function is able to:\n<ul>\n<li>read a desired number of characters (including just one) from the file, and return them as a string;<\/li>\n<li>read all the file contents, and return them as a string;<\/li>\n<li>if there is nothing more to read (the virtual reading head reaches the end of the file), the function returns an empty string.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<pre class=\"lang:default decode:true\"># Opening tzop.txt in read mode, returning it as a file object:\r\nstream = open(\"tzop.txt\", \"rt\", encoding = \"utf-8\")\r\n\r\nprint(stream.read()) # printing the content of the file<\/pre>\n<p><code>Beautiful is better than ugly.<\/code><br \/>\n<code>Explicit is better than implicit.<\/code><br \/>\n<code>Simple is better than complex.<\/code><br \/>\n<code>Complex is better than complicated.<\/code><\/p>\n<p>or<\/p>\n<pre class=\"lang:default decode:true\">from os import strerror\r\n\r\ntry:\r\n    cnt = 0\r\n    s = open('text.txt', \"rt\")\r\n    ch = s.read(1)\r\n    while ch != '':\r\n        print(ch, end='')\r\n        cnt += 1\r\n        ch = s.read(1)\r\n    s.close()\r\n    print(\"\\n\\nCharacters in file:\", cnt)\r\nexcept IOError as e:\r\n    print(\"I\/O error occurred: \", strerror(e.errno))<\/pre>\n<p><code>Beautiful is better than ugly.<\/code><br \/>\n<code>Explicit is better than implicit.<\/code><br \/>\n<code>Simple is better than complex.<\/code><br \/>\n<code>Complex is better than complicated.<\/code><\/p>\n<p><code>Characters in file: 131<\/code><\/p>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul>\n<li><strong><code>readline()<\/code><\/strong> \u2013 reads a single line from the text file; The optional parameter of the method can be used to specify the number of bytes of the file that we need to read.<\/li>\n<\/ul>\n<\/li>\n<li style=\"list-style-type: none;\">\n<pre class=\"lang:default decode:true\">from os import strerror\r\n\r\ntry:\r\n    ccnt = lcnt = 0\r\n    s = open('text.txt', 'rt')\r\n    line = s.readline()\r\n    while line != '':\r\n        lcnt += 1\r\n        for ch in line:\r\n            print(ch, end='')\r\n            ccnt += 1\r\n        line = s.readline()\r\n    s.close()\r\n    print(\"\\n\\nCharacters in file:\", ccnt)\r\n    print(\"Lines in file:     \", lcnt)\r\nexcept IOError as e:\r\n    print(\"I\/O error occurred:\", strerror(e.errno))<\/pre>\n<p><code>Beautiful is better than ugly.<\/code><br \/>\n<code>Explicit is better than implicit.<\/code><br \/>\n<code>Simple is better than complex.<\/code><br \/>\n<code>Complex is better than complicated.<\/code><br \/>\n<code><\/code><\/li>\n<li style=\"list-style-type: none;\"><code>Characters in file: 131<\/code><code><\/code><\/li>\n<li style=\"list-style-type: none;\"><code>Lines in file: 4<\/code><\/li>\n<\/ul>\n<p>&nbsp;<\/p>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul>\n<li><code><strong>readlines(number)<\/strong><\/code> \u2013 reads a file and returns all its lines as a list. The optional parameter of the method can specify the number of bytes of the file that we need to read. Returns a list of strings, one element per file line.<\/li>\n<\/ul>\n<\/li>\n<li style=\"list-style-type: none;\">\n<pre class=\"lang:default decode:true\">from os import strerror\r\n\r\ntry:\r\n    ccnt = lcnt = 0\r\n    s = open('text.txt', 'rt')\r\n    lines = s.readlines(20)\r\n    while len(lines) != 0:\r\n        for line in lines:\r\n            lcnt += 1\r\n            for ch in line:\r\n                print(ch, end='')\r\n                ccnt += 1\r\n        lines = s.readlines(10)\r\n    s.close()\r\n    print(\"\\n\\nCharacters in file:\", ccnt)\r\n    print(\"Lines in file:     \", lcnt)\r\nexcept IOError as e:\r\n    print(\"I\/O error occurred:\", strerror(e.errno))<\/pre>\n<p><code>Beautiful is better than ugly.<\/code><br \/>\n<code>Explicit is better than implicit.<\/code><br \/>\n<code>Simple is better than complex.<\/code><br \/>\n<code>Complex is better than complicated.<\/code><\/p>\n<p><code>Characters in file: 131<\/code><br \/>\n<code>Lines in file: 4<\/code><\/li>\n<\/ul>\n<p>&nbsp;<\/p>\n<p>8. To write new content into a file, the following stream methods can be used:<\/p>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul>\n<li><strong><code>write(string)<\/code><\/strong> \u2013 writes a <code>string<\/code> to a text file;<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<pre class=\"lang:default decode:true\">from os import strerror\r\n\r\ntry:\r\n\tfo = open('newtext.txt', 'wt') # A new file (newtext.txt) is created.\r\n\tfor i in range(10):\r\n\t\ts = \"line #\" + str(i+1) + \"\\n\"\r\n\t\tfor ch in s:\r\n\t\t\tfo.write(ch)\r\n\tfo.close()\r\nexcept IOError as e:\r\n\tprint(\"I\/O error occurred: \", strerror(e.errno))<\/pre>\n<p>The code creates a file filled with the following text:<br \/>\n<code>line #1<\/code><br \/>\n<code>line #2<\/code><br \/>\n<code>line #3<\/code><br \/>\n<code>line #4<\/code><br \/>\n<code>line #5<\/code><br \/>\n<code>line #6<\/code><br \/>\n<code>line #7<\/code><br \/>\n<code>line #8<\/code><br \/>\n<code>line #9<\/code><br \/>\n<code>line #10<\/code><\/p>\n<p>Writing whole lines to the text file:<\/p>\n<pre class=\"lang:default decode:true \">from os import strerror\r\n\r\ntry:\r\n    fo = open('newtext.txt', 'wt')\r\n    for i in range(10):\r\n        fo.write(\"line #\" + str(i+1) + \"\\n\")\r\n    fo.close()\r\nexcept IOError as e:\r\n    print(\"I\/O error occurred: \", strerror(e.errno))<\/pre>\n<p>if you want to send a message string to stderr to distinguish it from normal program output, it may look like this:<\/p>\n<pre class=\"lang:default decode:true \">import sys\r\nsys.stderr.write(\"Error message\")\r\n\r\n<\/pre>\n<p>&nbsp;<\/p>\n<p>9. The <code><strong>open()<\/strong><\/code> method returns an iterable object which can be used to iterate through all the file&#8217;s lines inside a <code>for<\/code> loop. For example:<\/p>\n<pre class=\"lang:default decode:true \">for line in open(\"file\", \"rt\"):\r\n    print(line, end='')\r\n\r\n<\/pre>\n<p>The code copies the file&#8217;s contents to the console, line by line.<\/p>\n<p><b>Note<\/b>: the stream closes itself <b>automatically<\/b> when it reaches the end of the file.<\/p>\n<pre class=\"lang:default decode:true\">from os import strerror\r\n\r\ntry:\r\n\tccnt = lcnt = 0\r\n\tfor line in open('text.txt', 'rt'):\r\n\t\tlcnt += 1\r\n\t\tfor ch in line:\r\n\t\t\tprint(ch, end='')\r\n\t\t\tccnt += 1\r\n\tprint(\"\\n\\nCharacters in file:\", ccnt)\r\n\tprint(\"Lines in file:     \", lcnt)\r\nexcept IOError as e:\r\n\tprint(\"I\/O error occurred: \", strerror(e.errno))<\/pre>\n<p><code>Beautiful is better than ugly.<\/code><br \/>\n<code>Explicit is better than implicit.<\/code><br \/>\n<code>Simple is better than complex.<\/code><br \/>\n<code>Complex is better than complicated.<\/code><\/p>\n<p><code>Characters in file: 131<\/code><br \/>\n<code>Lines in file: 4<\/code><\/p>\n<p>&nbsp;<\/p>\n<p>10. <strong>Amorphous data<\/strong> is data which have no specific shape or form &#8211; they are just a series of bytes.\u00a0Amorphous data cannot be stored using any of the previously presented means &#8211; they are neither strings nor lists. There should be a special container able to handle such data.\u00a0Python has more than one such container &#8211; one of them is a specialized class name<strong> bytearray<\/strong> &#8211; as the name suggests, it&#8217;s <strong>an array containing (amorphous) bytes<\/strong>.<\/p>\n<pre class=\"lang:default decode:true \">data = bytearray(10)<\/pre>\n<p>Such an invocation creates a bytearray object able to store ten bytes.<\/p>\n<p>Note: such a constructor <strong>fills the whole array with zeros<\/strong>.<\/p>\n<p>Bytearrays resemble lists in many respects. For example, they are <strong>mutable<\/strong>, they&#8217;re a subject of the <code>len()<\/code> function, and you can access any of their elements using conventional indexing.<\/p>\n<p>There is one important limitation &#8211; <strong>you mustn&#8217;t set any byte array elements with a value which is not an integer<\/strong> (violating this rule will cause a <span style=\"font-family: Courier New;\">TypeError<\/span> exception) and you&#8217;re <strong>not allowed to assign a value that doesn&#8217;t come from the range 0 to 255 inclusive<\/strong> (unless you want to provoke a <span style=\"font-family: Courier New;\">ValueError<\/span> exception).<\/p>\n<p>You can <strong>treat any byte array elements as integer values<\/strong> &#8211; just like in the example in the editor.<\/p>\n<pre class=\"lang:default decode:true \">data = bytearray(10)\r\n\r\nfor i in range(len(data)):\r\n    data[i] = 10 - i\r\n\r\nfor b in data:\r\n    print(hex(b))\r\n<\/pre>\n<p><code>0xa<\/code><br \/>\n<code>0x9<\/code><br \/>\n<code>0x8<\/code><br \/>\n<code>0x7<\/code><br \/>\n<code>0x6<\/code><br \/>\n<code>0x5<\/code><br \/>\n<code>0x4<\/code><br \/>\n<code>0x3<\/code><br \/>\n<code>0x2<\/code><br \/>\n<code>0x1<\/code><\/p>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul>\n<li><code><strong>write(bytearray)<\/strong><\/code> \u2013 writes all the bytes of <code>bytearray<\/code> to a file;<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<pre class=\"lang:default decode:true\">from os import strerror\r\n\r\ndata = bytearray(10)\r\n\r\nfor i in range(len(data)):\r\n    data[i] = 10 + i\r\n\r\ntry:\r\n    bf = open('file.bin', 'wb')\r\n    bf.write(data)\r\n    bf.close()\r\nexcept IOError as e:\r\n    print(\"I\/O error occurred:\", strerror(e.errno))\r\n\r\n# Your code that reads bytes from the stream should go here.\r\n<\/pre>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul>\n<li>Reading from a binary file requires use of a specialized method name <code><strong>readinto(bytearray)<\/strong><\/code>, as the method doesn&#8217;t create a new byte array object, but fills a previously created one with the values taken from the binary file.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<pre class=\"lang:default decode:true\">from os import strerror\r\n\r\ndata = bytearray(10)\r\n\r\ntry:\r\n    bf = open('file.bin', 'rb')\r\n    bf.readinto(data)\r\n    bf.close()\r\n\r\n    for b in data:\r\n        print(hex(b), end=' ')\r\nexcept IOError as e:\r\n    print(\"I\/O error occurred:\", strerror(e.errno))<\/pre>\n<p>An alternative way of reading the contents of a binary file is offered by the method named <code>read()<\/code>.<\/p>\n<pre class=\"lang:default decode:true \">from os import strerror\r\n\r\ntry:\r\n    bf = open('file.bin', 'rb')\r\n    data = bytearray(bf.read())\r\n    bf.close()\r\n\r\n    for b in data:\r\n        print(hex(b), end=' ')\r\n\r\nexcept IOError as e:\r\n    print(\"I\/O error occurred:\", strerror(e.errno))\r\n\r\n<\/pre>\n<p>This class has some similarities to <code>bytearray<\/code>, with the exception of one significant difference &#8211; it&#8217;s <strong>immutable<\/strong>. Be careful &#8211; <strong>don&#8217;t use this kind of read if you&#8217;re not sure that the file&#8217;s contents will fit the available memory<\/strong>.<\/p>\n<p>f the <code>read()<\/code> method is invoked with an argument, it <strong>specifies the maximum number of bytes to be read<\/strong>.<\/p>\n<pre class=\"lang:default decode:true \">try:\r\n    bf = open('file.bin', 'rb')\r\n    data = bytearray(bf.read(5))\r\n    bf.close()\r\n\r\n    for b in data:\r\n        print(hex(b), end=' ')\r\n\r\nexcept IOError as e:\r\n    print(\"I\/O error occurred:\", strerror(e.errno))\r\n\r\n<\/pre>\n<p>&nbsp;<\/p>\n<p><strong>Copying files<\/strong><\/p>\n<pre class=\"lang:default decode:true \">from os import strerror\r\n\r\nsrcname = input(\"Enter the source file name: \")\r\ntry:\r\n    src = open(srcname, 'rb')\r\nexcept IOError as e:\r\n    print(\"Cannot open the source file: \", strerror(e.errno))\r\n    exit(e.errno)\t\r\n\r\ndstname = input(\"Enter the destination file name: \")\r\ntry:\r\n    dst = open(dstname, 'wb')\r\nexcept Exception as e:\r\n    print(\"Cannot create the destination file: \", strerror(e.errno))\r\n    src.close()\r\n    exit(e.errno)\t\r\n\r\nbuffer = bytearray(65536)\r\ntotal  = 0\r\ntry:\r\n    readin = src.readinto(buffer)\r\n    while readin &gt; 0:\r\n        written = dst.write(buffer[:readin])\r\n        total += written\r\n        readin = src.readinto(buffer)\r\nexcept IOError as e:\r\n    print(\"Cannot create the destination file: \", strerror(e.errno))\r\n    exit(e.errno)\t\r\n    \r\nprint(total,'byte(s) succesfully written')\r\nsrc.close()\r\ndst.close()<\/pre>\n<p>&nbsp;<\/p>\n<p><em>Exercise 1<\/em><\/p>\n<p>How do you encode an <code>open()<\/code> function\u2019s <code>mode<\/code> argument value if you&#8217;re going to create a new text file to only fill it with an article?<\/p>\n<p id=\"sol\"><code>\"wt\"<\/code> or <code>\"w\"<\/code><\/p>\n<p>&nbsp;<\/p>\n<p><em>Exercise 2<\/em><\/p>\n<p>What is the meaning of the value represented by <code>errno.EACCES<\/code>?<\/p>\n<p id=\"sol2\"><b>Permission denied<\/b>: you&#8217;re not allowed to access the file&#8217;s contents.<\/p>\n<p>&nbsp;<\/p>\n<p><em>Exercise 3<\/em><\/p>\n<p>What is the expected output of the following code, assuming that the file named <i>file<\/i> does not exist?<\/p>\n<pre class=\"lang:default decode:true \">import errno\r\n\r\ntry:\r\n    stream = open(\"file\", \"rb\")\r\n    print(\"exists\")\r\n    stream.close()\r\nexcept IOError as error:\r\n    if error.errno == errno.ENOENT:\r\n        print(\"absent\")\r\n    else:\r\n        print(\"unknown\")<\/pre>\n<p>&nbsp;<\/p>\n<p id=\"sol3\"><code class=\"codep \">absent<\/code><\/p>\n<p>&nbsp;<\/p>\n<p><em>Exercise 4<\/em><\/p>\n<p>What do we expect from the <code>readlines()<\/code> method when the stream is associated with an empty file?<\/p>\n<p>&nbsp;<\/p>\n<p id=\"sol\">An empty list (a zero-length list).<\/p>\n<p><em>Exercise 5<\/em><\/p>\n<p>What is the following code intended to do?<\/p>\n<pre class=\"lang:default decode:true \">for line in open(\"file\", \"rt\"):\r\n    for char in line:\r\n        if char.lower() not in \"aeiouy \":\r\n            print(char, end='')<\/pre>\n<p>&nbsp;<\/p>\n<p id=\"sol2\">It copies the <i>file<\/i>&#8216;s contents to the console, ignoring all vowels.<\/p>\n<p><em>Exercise 6<\/em><\/p>\n<p>You&#8217;re going to process a bitmap stored in a file named <code>image.png<\/code>, and you want to read its contents as a whole into a <i>bytearray<\/i> variable named <code>image<\/code>. Add a line to the following code to achieve this goal.<\/p>\n<pre class=\"lang:default decode:true \">try:\r\n    stream = open(\"image.png\", \"rb\")\r\n    # Insert a line here.\r\n    stream.close()\r\nexcept IOError:\r\n    print(\"failed\")\r\nelse:\r\n    print(\"success\")<\/pre>\n<p>&nbsp;<\/p>\n<p><code>image = bytearray(stream.read())<\/code><\/p>\n<p><em>Exercise 7.<\/em><\/p>\n<p>What is the expected output of the following code (assuming file <code>myfile.txt<\/code> exists and is not empty) ?<\/p>\n<pre class=\"lang:default decode:true\">f = open(\"myfile.txt\", \"r\")\r\nprint(f.readline(20))<\/pre>\n<p>The code will read and print out the first 20 bytes of the first line from file <code>myfile.txt<\/code><\/p>\n<p><strong>Explanation:<\/strong><\/p>\n<p>The <code>readline()<\/code> method returns one line from the file. The optional parameter specifies the number of bytes from the line to return (default -1, which means the whole line).<\/p>\n<p>&nbsp;<\/p>\n<p>Exercise 8.<\/p>\n<div id=\"question-prompt\" class=\" ud-text-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p>You want to print the content of a text file named <em>myfile.txt<\/em> to the screen.<\/p>\n<p>Assuming the file exists and includes 10 lines of text (each line containing less than 10 characters), which code snippet can produce the expected result ? (Pick two)<\/p>\n<p>A<\/p>\n<pre class=\"lang:default decode:true \">    f = open('myfile.txt', 'r')\r\n    data = f.read()\r\n    for x in data:\r\n        print(x, end='')\r\n    f.close()<\/pre>\n<p>B<\/p>\n<pre class=\"lang:default decode:true\">    f = open('myfile.txt', 'r')\r\n    data = f.readlines(10)\r\n    print(data)\r\n    f.close()<\/pre>\n<\/div>\n<p>C<\/p>\n<pre class=\"lang:default decode:true \">    f = open('myfile.txt', 'rt')\r\n    data = f.readline()\r\n    print(data)\r\n    f.close()<\/pre>\n<p>D<\/p>\n<pre class=\"lang:default decode:true \">    for line in open(\"myfile.txt\", \"rt\"):\r\n        print(line, end='')<\/pre>\n<p>&nbsp;<\/p>\n<p>AD<\/p>\n<p><strong>Explanation:<\/strong><\/p>\n<p><code>readline(number)<\/code> is used to read <strong>a single line<\/strong> from a <strong>text <\/strong>file; <code>number<\/code> is optional : this is the maximum <code>number<\/code> of characters\/bytes to read from the line.\u00a0 If <code>number<\/code>\u00a0 is omitted the whole line is read. Note that <code>readline()<\/code> returns a string.<\/p>\n<p><code>readlines(number)<\/code> is used to read <strong>the lines<\/strong> from a <strong>text <\/strong>file; <code>number<\/code> is optional : If the number of bytes returned exceed this number, no more lines will be returned. If <code>number<\/code> is omitted, all lines are read. Note that <code>readlines()<\/code> returns a <strong>list of strings<\/strong>, one element per file line.<\/p>\n<p><code>read(number)<\/code> is used to read the <code>number<\/code> characters\/bytes from a file and returns them as a string &#8211; if <code>number<\/code>\u00a0 is omitted the whole file is read.<\/p>\n<p>Now, let&#8217;s review the suggested answers:<\/p>\n<p>A\/ This would work<\/p>\n<p>B\/ This would only print a few lines from the file, as a list. Exact number of lines would depend on the number of characters in each line &#8211; Indeed,\u00a0 <code>f.readlines(10)<\/code> would stop processing any new lines after the 10 first bytes have been read.<\/p>\n<p>C\/ This would only print the first line of the file<\/p>\n<p>D\/ This would work<\/p>\n<p>&nbsp;<\/p>\n<p>Ex.9<\/p>\n<p>You want to read the content of file Stars.txt file and retrieve its first five lines. You started writing the following Python snippet:<\/p>\n<pre class=\"lang:default decode:true \">    f = open('Stars.txt','rt')    # Line 1 \r\n    # insert code here            # Line 2\r\n    f.close()                     # Line 3<\/pre>\n<p>Explanation:<\/p>\n<p><code>readline(number)<\/code> is used to read <strong>a single line<\/strong> from a <strong>text <\/strong>file; <code>number<\/code> is optional : this is the maximum <code>number<\/code> of characters\/bytes to read from the line.\u00a0 If <code>number<\/code>\u00a0 is omitted the whole line is read.<\/p>\n<p><code>readlines(number)<\/code> is used to read <strong>the lines<\/strong> from a <strong>text <\/strong>file; <code>number<\/code> is optional : If the number of bytes returned exceed this number, no more lines will be returned. If <code>number<\/code> is omitted, all lines are read.<\/p>\n<p><code>read(number)<\/code> is used to read the <code>number<\/code> characters\/bytes from a file and returns them as a string &#8211; if <code>number<\/code>\u00a0 is omitted the whole file is read.<\/p>\n<p>Now, let&#8217;s review the suggested answers:<\/p>\n<p><code>data = f.readlines(5)<\/code>\u00a0 would only read the first line since the first line has more than 5 characters (and no more lines will be returned because of the maximum bytes parameter 5)<\/p>\n<p><code>data = f.readline(5)<\/code>\u00a0 would only read the first 5 characters of the first line.<\/p>\n<p><code>data = f.read(5)<\/code>\u00a0 would only read the first 5 characters of the whole file.<\/p>\n<p><code>data = f.readlines()[:5] <\/code>\u00a0 This will read all lines from the file and then slice the resulting list to its first 5 elements, which is what we need here.<\/p>\n<p>Try it yourself:<\/p>\n<pre class=\"lang:default decode:true \">    # this code is to create the file Stars.txt - this creates a files with 10 lines\r\n    try:\r\n        f = open('Stars.txt', 'wt')\r\n        for i in range(10):\r\n            s = \"line #\" + str(i+1) + \"\\n\"\r\n            f.write(s)\r\n        f.close()\r\n    except:\r\n        print(\"I\/O error occurred:\")\r\n    # End of code\r\n     \r\n    # Now this part of the code is to read the file Stars.txt                                        \r\n    f = open('Stars.txt', 'rt')     \r\n    data = f.readlines()[:5]             \r\n    f.close()                                                   \r\n     \r\n    # Now print the content from variable data to check if we read the file correctly:\r\n    print(data)        # ['line #1\\n', 'line #2\\n', 'line #3\\n', 'line #4\\n', 'line #5\\n']<\/pre>\n<p>&nbsp;<\/p>\n<p>Ex. 10<\/p>\n<p>What is the expected output of the following code, assuming the file <code>myfile.txt<\/code> does <strong>not <\/strong>exist ?<\/p>\n<pre class=\"lang:default decode:true\">    f = open(\"myfile.txt\", \"at\")\r\n    for i in range(1,11):\r\n        f.write('Line #' + str(i) + '\\n')\r\n    f.seek(0)\r\n    print(f.readline(10))\r\n    f.close()<\/pre>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-skipped--1NDPn\" data-purpose=\"answer\">\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p>A. The code will print out the first 10 lines of the file <code>myfile.txt<\/code> .<\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-incorrect--vFyOv\" data-purpose=\"answer\">\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p>B. The code will print out the first 10 bytes of the first line of the file <code>myfile.txt<\/code> .<\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-skipped--1NDPn\" data-purpose=\"answer\">\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p>C. The code will raise an unhandled exception because the file <code>myfile.txt<\/code>\u00a0 did not exist prior to the execution of the <code>open()<\/code> function.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-correct--PLOEU\" data-purpose=\"answer\">\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p>D. The code will raise an unhandled exception.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--question-related-fields--c3m--\">\n<div class=\"overall-explanation-pane--overall-explanation--G-hLQ ud-form-group\">\n<div id=\"overall-explanation\" class=\"ud-text-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p>&nbsp;<\/p>\n<p><em>Explanation:<\/em><\/p>\n<p>The file <code>myfile.txt<\/code>\u00a0 is being opened using the <code>'at'<\/code> parameter, which means &#8220;append&#8221; (<code>'a'<\/code>) and &#8220;text&#8221; (<code>'t'<\/code>).<\/p>\n<p>In the <strong>append <\/strong>mode, the file associated with the stream <strong>doesn&#8217;t need to exist<\/strong>; if it doesn&#8217;t exist, it will be created; if it exists the previous content of the file remains untouched and any data written to the file will be inserted at the end, after the existing data. Also, in this mode, <strong>the file cannot be read<\/strong> &#8211; it is only open for writing.<\/p>\n<p>So, line of code <code>print(f.readline(10))<\/code> will raise an unhandled exception because the file cannot be read in the <code>'a'<\/code> (append) mode.<\/p>\n<p>So, the correct answer is : <em>The code will raise an unhandled exception.<\/em><\/p>\n<p>If the file had been opened in the <em>Append and Read<\/em> mode (<code>'a+'<\/code>), then the code would have been executed correctly and the first 10 bytes of the first line of the file <code>myfile.txt<\/code>\u00a0 would have been printed out (as a reminder the <code>readline()<\/code> method returns one line from the file; the optional parameter specifies the number of bytes from the line to return (default -1, which means the whole line)).<\/p>\n<p>Try it yourself:<\/p>\n<pre class=\"lang:default decode:true \">    # with the append mode:\r\n    f = open(\"myfile.txt\", \"at\")\r\n    for i in range(1,11):\r\n        f.write('Line #' + str(i) + '\\n')\r\n    f.seek(0)\r\n    print(f.readline(10))    # Exception\r\n    f.close()\r\n     \r\n    # with the append and read mode:\r\n    f = open(\"myfile2.txt\", \"a+t\")\r\n    for i in range(1,11):\r\n        f.write('Line #' + str(i) + '\\n')\r\n    f.seek(0)\r\n    print(f.readline(10))    # Line #1\r\n    f.close()<\/pre>\n<p>D.<\/p>\n<p>&nbsp;<\/p>\n<p>Ex. 11<\/p>\n<p>What is the expected output of the following code, assuming the file <code>myfile.txt<\/code> does <strong>not <\/strong>exist ?<\/p>\n<\/div>\n<\/div>\n<\/div>\n<pre class=\"lang:default decode:true \">    L = [\"ABC\\n\" for x in range(10)]\r\n    f = open(\"myfile.txt\", \"w+\")\r\n    f.writelines(L)\r\n    print(f.read())\r\n    f.close()<\/pre>\n<p>&nbsp;<\/p>\n<p>Explanation:<\/p>\n<p>The first line of the code will create a list <code>L<\/code> containing 10 elements &#8211; each element being the string <code>\"ABC\\n\"<\/code>.<\/p>\n<p>The file <code>myfile.txt<\/code>\u00a0 is being open in mode <code>\"w+\"<\/code> which means <em>write and update<\/em>. In this mode, the file associated with the stream doesn&#8217;t need to exist; if it doesn&#8217;t exist, it will be created; both read and write operations are allowed for the stream.<\/p>\n<p>The <code>writelines()<\/code> method writes the items of a list to a file.<\/p>\n<p>So, the first three lines of the above code will work correctly (no exception is raised) : the content of the list <code>L<\/code> will be printed to the file.<\/p>\n<p>The 4th line of the code will print the content of the file to the screen but <strong>starting at the current file position<\/strong> (end of the file at this point) and so no visible character will be printed out.<\/p>\n<p>So, the correct answer is : <strong><em>The code will not raise an exception but will not print any visible characters.<\/em><\/strong><\/p>\n<p>To allow the whole content of the file to be printed to the screen correctly, <strong>the file position should have been reset to the beginning of the file<\/strong> &#8211; this can be done using the method <code>seek() <\/code>which allows to move the stream reader to a particular location in the stream. In the above code adding <code>f.seek(0)<\/code> prior to the line <code>print(f.read())<\/code> would have printed all 11 lines of the file to the screen.<\/p>\n<p>Try it yourself:<\/p>\n<pre class=\"lang:default decode:true \">    # Nothing is printed to the screen with this code:\r\n    L = [\"ABC\\n\" for x in range(10)]\r\n    f = open(\"myfile.txt\", \"w+\")\r\n    f.writelines(L)\r\n    print(f.read())\r\n    f.close()\r\n     \r\n    # Here using seek() method to reset the file position to the beginning:\r\n    L = [\"ABC\\n\" for x in range(10)]\r\n    f = open(\"myfile2.txt\", \"w+\")\r\n    f.writelines(L)\r\n    f.seek(0)\r\n    print(f.read())\r\n    f.close()<\/pre>\n<p>&nbsp;<\/p>\n<p>Ex. 12<\/p>\n<p>What is the expected output of the following code, assuming that the file named <em>myfile.txt<\/em> does exist?<\/p>\n<pre class=\"lang:default decode:true \">    import errno\r\n     \r\n    try:\r\n        data = open(\"myfile.txt\", \"x\")\r\n        data.write(\"123\")\r\n        data.close()\r\n    except IOError as e:\r\n        if e.errno == errno.ENOENT:\r\n            print(\"A\")\r\n        elif e.errno == errno.EEXIST:\r\n            print(\"B\")\r\n        else:\r\n            print(\"C\")\r\n    else:\r\n        print(\"D\")<\/pre>\n<p>&nbsp;<\/p>\n<p><strong>Explanation:<\/strong><\/p>\n<p>The <code>IOError<\/code> exception object is equipped with a property named <code>errno<\/code>.<\/p>\n<p>The value of the <code>errno<\/code> property can be compared with one of the predefined symbolic constants defined in the <code>errno<\/code> module.<\/p>\n<p>The most common ones are:<\/p>\n<p><code>errno.ENOENT<\/code> : No such file or directory<\/p>\n<p><code>errno.EACCES<\/code> : permission denied<\/p>\n<p><code>errno.EEXIST<\/code> : file already exists<\/p>\n<p>In the above question, <em>myfile.txt<\/em> is being opened with the <code>x<\/code> mode. With the <code>x<\/code> mode, the file will be opened for <strong>exclusive creation<\/strong> : The file must not exist before <code>open<\/code>\u00a0 and\u00a0 the file will be created after <code>open<\/code>. If if the file already exists when opening it with the <code>x<\/code> mode, then an exception <em>FileExistsError <\/em>will be raised. This exception is equivalent to an <code>IOError<\/code>\u00a0 exception with errno value equal to <code>errno.EEXIST<\/code> .<\/p>\n<p>Because <em>myfile.txt<\/em> already exists when line of code <code>data = open(\"myfile.txt\", \"x\") <\/code>is executed, this will raise an exception and the <code>errno <\/code>attribute from the <code>IOError<\/code> exception object\u00a0 <code>e<\/code> will be equal to <code>errno.EEXIST<\/code> (file already exists) and consequently, <code>B<\/code> will be printed.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Due to the type of the stream&#8217;s contents, all the streams are divided into text and binary streams. The text streams ones are structured in lines; that is, they contain typographical characters (letters, digits, punctuation, etc.) arranged in rows (lines), as seen with the naked eye when you look at the contents of the file &hellip; <\/p>\n<p class=\"link-more\"><a href=\"http:\/\/miro.borodziuk.eu\/index.php\/2022\/05\/20\/file-processing-in-python\/\" class=\"more-link\">Continue reading<span class=\"screen-reader-text\"> &#8220;File processing in Python&#8221;<\/span><\/a><\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[100],"tags":[],"_links":{"self":[{"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/posts\/6106"}],"collection":[{"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/comments?post=6106"}],"version-history":[{"count":43,"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/posts\/6106\/revisions"}],"predecessor-version":[{"id":6268,"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/posts\/6106\/revisions\/6268"}],"wp:attachment":[{"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/media?parent=6106"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/categories?post=6106"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/tags?post=6106"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}