Python Count Words In Text File Example

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

1. Python Get Text File Words Count 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 the project file package explorer panel.
    get text file words count in python example
Created on Aug 18, 2018
@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
0 0 votes
Article Rating
Notify of

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

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x