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>The first thing that jumps out is the lack of consistency and readability: in some lines you indent with 4 spaces, on others you only use two; in some places you put a space after a comma, in others you don't, in most places you don't have spaces around the assignment operator (<code>=</code>)...</p>

<p>Be consistent and make your code readable. The most commonly used formatting is to use four spaces for indenting and to always have a space after a comma but even more important than that is to be consistent, meaning that whatever you choose, stick with it throughout your code. It makes it much easier to read for everyone, including yourself.</p>

<p>Here are a few other things I think you could improve:</p>

<ul>
<li><p>Have a single exception handling block instead of two.</p></li>
<li><p>You can also open both files in a single line.</p></li>
<li><p>Even better, combine both previous suggestions and have a separate method to read data from the files, thus eliminating code repetition and making the main method easier to read.</p></li>
<li><p>For string formatting it's preferred to use <code>.format()</code> instead of <code>%</code>. Check this out: <a href="https://pyformat.info/" rel="nofollow">https://pyformat.info/</a></p></li>
<li><p>Overall try to avoid repetition in your code. If there's something you're doing more than once, extract it to a separate function or method and use that instead.</p></li>
</ul>

<p>Here's your code quickly modified to how I'd probably write it, and taking these things into account:</p>

<pre><code>import sys


class AtifImam:
    def __init__(self):
        self.freq_dictionary = {}

    def form_density_dictionary(self, word_file, exclude_file):
        words_excluded = self.read_words_list(exclude_file)
        words_excluded = self.lowercase(words_excluded)

        words_list = self.read_words_list(word_file)
        if len(words_list) == 0:
            print("** No data in file: {} **".format(word_file))
            sys.exit()

        words_list = self.lowercase(words_list)

        unique_words = list((set(words_list) - set(words_excluded)))

        self.freq_dictionary = {
            word: ("{:6.2f}".format(
                float((words_list.count(word)) / len(words_list)) * 100))
            for word in unique_words
            }

    @staticmethod
    def read_words_list(file_name):
        try:
            with open(file_name, 'r') as file:
                data = file.read()
                print("**  Read file successfully: {} **".format(file_name))
                return data.split()
        except IOError as e:
            print("** Could not read file: {0.filename} **".format(e))
            sys.exit()

    @staticmethod
    def lowercase(word_list):
        return [word.lower() for word in word_list]
</code></pre>

python python-3.x error-handling