How do I perform error handling with two files?
<p>So , I am having two files , so to checks its validity  I am performing <code>try</code> and <code>except</code> two times . But I don't thinks this is a good method, can you suggest a better way?</p>

<p>Here is my code:</p>

<pre><code>def form_density_dictionary(self,word_file,fp_exclude):
  self.freq_dictionary={}
  try:
      with open(fp_exclude,'r')as fp2:
          words_excluded=fp2.read().split() #words to be excluded stored in a list
          print("**Read file successfully :" + fp_exclude + "**")
          words_excluded=[words.lower() for words in words_excluded] # converted to lowercase

  except IOError:
      print("**Could not read file:", fp_exclude, " :Please check file name**")
      sys.exit()

  try:
      with open(word_file,'r') as file:
          print("**Read file successfully :" + word_file + "**")
          words_list=file.read()
          if not words_list:
              print("**No data in file:",word_file +":**")
              sys.exit()
          words_list=words_list.split()
          words_list=[words.lower() for words in words_list] # lowercasing entire list
      unique_words=list((set(words_list)-set(words_excluded)))

      self.freq_dictionary= {word:("%6.2f"%(float((words_list.count(word))/len(words_list))*100))  for word in unique_words}
      #print((len(self.freq_dictionary)))
  except IOError:
      print("**Could not read file:", word_file, " :Please check file name**")
      sys.exit()
</code></pre>

<p>Any other suggestion is also welcomed to make it more pythonic.</p>

<p>Exceptions thrown that involve a file system path have a <code>filename</code> attribute that can be used instead of explicit attributes <code>word_file</code> and <code>fp_exclude</code> as you do. </p>

<p>This means you can wrap these IO operations in the same <code>try-except</code> and use the <code>exception_instance.filename</code> which will indicate in which file the operation couldn't be performed.</p>

<p>For example:</p>

<pre><code>try:
    with open('unknown_file1.py') as f1, open('known_file.py') as f2:
        f1.read()
        f2.read()
except IOError as e:
    print("No such file: {0.filename}".format(e))
</code></pre>

<p>Eventually prints out:</p>

<pre><code>No such file: unknown_file1.py
</code></pre>

<p>While the opposite:</p>

<pre><code>try:
    with open('known_file.py') as f1, open('unknown_file2.py') as f2:
        f1.read()
        f2.read()
except IOError as e:
    print("No such file: {0.filename}".format(e))
</code></pre>

<p>Prints out:</p>

<pre><code>No such file: unknown_file2.py
</code></pre>

python python-3.x error-handling