Python Count Words In Text File Example

This example tells you how to read text file content and get the words count number in the text file use python. This example is created with the eclipse PyDev plugin, you can read an article in the reference section to learn more about PyDev.

1. Python Get Text File Words Count Number Project Creation Steps.

  1. Open Eclipse PyDev.
  2. Click File —> New —> Others menu item, then select PyDev Package to create a package com.dev2qa.example.file.
  3. Click File —> New —> Others menu item, then select PyDev Module to create a module file
  4. Copy below source code into it.
  5. Right-click the source code, click Run As —> Python Run menu item to run the example.
  6. Below is this example source python code.
    @author: zhaosong
    # This function will read words count in a text file.
    def count_words_in_text_file(file_path):
        ret = -1
            # Open the text file.
            file_object = open(file_path, "r")
            # Get all file content in a string.
            file_content =
            # Split the file content into an array.
            words_array = file_content.split()
            # Get words array length.
            words_array_len = len(words_array)
            ret = words_array_len
            print(file_path + " contains " + str(words_array_len) + " words.")
        except FileNotFoundError:
            print(file_path + " do not exist. ")
        except PermissionError:
            print("You do not have permission to read file " + file_path)
        except IOError:
        return ret
    if __name__ == '__main__':


  1. How To Run Python In Eclipse With PyDev

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.