How do I perform error handling with two files?

Atif Imam

So , I am having two files , so to checks its validity I am performing try and except two times . But I don't thinks this is a good method, can you suggest a better way?

Here is my 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()

Any other suggestion is also welcomed to make it more pythonic.

borfast

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 (=)...

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.

Here are a few other things I think you could improve:

  • Have a single exception handling block instead of two.

  • You can also open both files in a single line.

  • 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.

  • For string formatting it's preferred to use .format() instead of %. Check this out: https://pyformat.info/

  • 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.

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

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]

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

How do I perform a mongodb two phase commit in grails?

From Dev

How do I merge two *.srt files

From Dev

How do I add general error handling into my React app?

From Dev

How do you perform p4 sync on two files in the same string

From Dev

I have two arrays, how do I find matchings elements and perform some action? (lodash)

From Dev

How do I share files between two computers connected to a router?

From Dev

How do I combine two hex files created by Keil uVision?

From Dev

How do I combine two text files line by line with Python?

From Dev

How do I compare two files with a shell script?

From Dev

How do I share files between two computers connected to a router?

From Dev

How do I copy columns of two files as rows of a third file

From Dev

How do I sync files between two drives?

From Dev

How do I merge two *.avi files into one

From Dev

How do I add numbers from two txt files with Bash?

From Dev

how do I compare two .js files in powershell

From Dev

How do I prevent two OSes from clobbering grub files?

From Dev

How do I concatenate the content of two files to make a third?

From Dev

How do I merge these two html/javascript files

From Dev

How do I link two HTML files present on the same server?

From Dev

How do I compare equality of two files in Ubuntu?

From Dev

How do I find and highlight differences between two text files?

From Java

How do I perform an IF...THEN in an SQL SELECT?

From Dev

How do I perform an "OR" filter on an aggregate?

From Dev

How do I perform decimal arithmetic in Perl?

From Dev

Excel: How do I perform bitwise counting?

From Dev

how do I perform multiplication to values in a column?

From Dev

How do I perform a Union in Dataflow?

From Dev

How do I perform a bitwise or (|) for enumerations in PowerShell?

From Dev

How Do I Perform Pagination with TinkerPop in Java?

Related Related

  1. 1

    How do I perform a mongodb two phase commit in grails?

  2. 2

    How do I merge two *.srt files

  3. 3

    How do I add general error handling into my React app?

  4. 4

    How do you perform p4 sync on two files in the same string

  5. 5

    I have two arrays, how do I find matchings elements and perform some action? (lodash)

  6. 6

    How do I share files between two computers connected to a router?

  7. 7

    How do I combine two hex files created by Keil uVision?

  8. 8

    How do I combine two text files line by line with Python?

  9. 9

    How do I compare two files with a shell script?

  10. 10

    How do I share files between two computers connected to a router?

  11. 11

    How do I copy columns of two files as rows of a third file

  12. 12

    How do I sync files between two drives?

  13. 13

    How do I merge two *.avi files into one

  14. 14

    How do I add numbers from two txt files with Bash?

  15. 15

    how do I compare two .js files in powershell

  16. 16

    How do I prevent two OSes from clobbering grub files?

  17. 17

    How do I concatenate the content of two files to make a third?

  18. 18

    How do I merge these two html/javascript files

  19. 19

    How do I link two HTML files present on the same server?

  20. 20

    How do I compare equality of two files in Ubuntu?

  21. 21

    How do I find and highlight differences between two text files?

  22. 22

    How do I perform an IF...THEN in an SQL SELECT?

  23. 23

    How do I perform an "OR" filter on an aggregate?

  24. 24

    How do I perform decimal arithmetic in Perl?

  25. 25

    Excel: How do I perform bitwise counting?

  26. 26

    how do I perform multiplication to values in a column?

  27. 27

    How do I perform a Union in Dataflow?

  28. 28

    How do I perform a bitwise or (|) for enumerations in PowerShell?

  29. 29

    How Do I Perform Pagination with TinkerPop in Java?

HotTag

Archive