How does this work: except IOError as e: print("No such file: {0.filename}".format(e))
<p>The code that uses the expression in question:</p>

<pre><code>def read_file(self,file_name):
        try:
            with open(file_name,'r') as file:
                data=file.read()
                return data.split()

        except IOError as e:
            print("Could not read file:{0.filename}".format(e))
            sys.exit()
</code></pre>

<p>How does this work? What is meaning of <code>{0.filename}.format(e)</code>? Why do we use <code>{0.filename}</code> and not <code>{1.filename}</code>?</p>

<p>This essentially means takes the positional argument at position <code>0</code> (in <code>format(e)</code>, <code>e</code> is the zero position arg)  and grab the <code>filename</code> attribute defined on it:</p>

<pre><code>print("No such file: {0.filename}".format(e))
</code></pre>

<p>Is similar to:</p>

<pre><code>print("No such file: {0}".format(e.filename))
</code></pre>

<p>It isn't <code>1.filename</code> because format hasn't been called with an argument at position <code>1</code>, another example might help you out even more:</p>

<pre><code>print("{0}{1.filename}".format("No such File: ", e))
</code></pre>

<p>Here <code>{0}</code> will grab <code>"No such File: "</code> and <code>{1.filename}</code> will grab <code>e.filename</code> and add it to the resulting string.</p>

python python-3.x