Create a Wordcounter in Python: How to Count Words and Lines in a File using Python?

Python Count The Number Of Lines & Words In A File

Hello readers! In this tutorial, we are going to discuss how to count the number of lines and words in a file using Python programming.

Also read: How to read a file in Python?


How to Count the Words and Lines – Python Wordcounter

Suppose you have a large file and need to figure out the number of words within the file. Along with that, you also want to find out how many lines of text are present within it. You can create a wordcounter program that does counts the words and the lines using Python.

1. Create a sample text file

In this process of creating a text file, we will first create a variable and assign a string to it. Then we will create a file in write only mode (‘w’) using the open() function and write the content of the string variable to the newly created text file. Finally, close the text file. Let’s write a Python program to create a text file.

# Create a Python string
string = """Welcome to AskPython!
AskPython is a part of JournalDev IT Services Private Limited."""

# Create a sample text file using open() function
file = open("sample_file.txt", "w", encoding='utf-8')

# Write the above string to the newly created text file
# If it is created successfully
if file != None:
    file.write(string)
    print("Sample text file created and written successfully!!")
else:
    print("OSError: File cannot be created!!")

# Close the above text file using close()
file.close()

Output:

Sample text file created and written successfully!!

2. Display the content of the sample text file

As we have successfully created a text file, we will now read the content of the sample text file into a variable using the read() function in read-only mode (‘r‘). Then we will print the content of the Python variable to view the text from our file. Finally, as a good practice, we will close the opened text to avoid any memory leaks in our code. Let’s see the Python code to read a given text file.

# Open the given sample text file using open() function
# In read only mode
file = open("C:path//sample_file.txt", "r", encoding='utf-8')

# Read the sample text file using the read() function
# If it is opened successfully
if file != None:
    file_data = file.read()
    # Print the content of the sample text file
    print("This is the content of the sample text file:\n")
    print(file_data)    
else:
    print("OSError: File cannot be opend!!")

# Close the above opened text file using close() function
file.close()

Output:

This is the content of the sample text file:

Welcome to AskPython!
AskPython is a part of JournalDev IT Services Private Limited.

3. Algorithm to count the number of lines and words in a file

To count the number of lines and words in a file, we have to follow the steps given below:

  1. Create two variables say line_count & word_count and initialize them with zero.
  2. Create another variable say file_path and initialize it with the full path of the given text file.
  3. Open the given text file in read only mode (‘r‘) using the open() function.
  4. Read the opened text file line by line and keep incrementing the line_count by one in each iteration.
  5. Count the number of words in each line being read using the len() and split() functions.
  6. Add the number of words in each line to the word_count.
  7. Close the opened text file using close() function.
  8. Print the final values of line_count and word_count variables.

4. Python code to count the number of lines and words in a file

Let’s implement the above algorithm to count the number of lines and words through Python code.

# Create two counter variables
# And initialize them with zero
line_count = 0
word_count = 0

# Open the given sample text file using open() function
file = open("C:path//sample_file.txt", "r", encoding='utf-8')

# Perform all the operations using the sample text file
# If it is opened successfully
if file != None:
    # Iterate over the opened file
    # To the number of lines and words in it
    for line in file:
        # Increment the line counter variable
        line_count = line_count + 1
        # Find the number of words in each line
        words = len(line.split())
        # Add the number of words in each line
        # To the word counter variable
        word_count = word_count + words 
else:
    print("OSError: File cannot be opend!!")

# Close the above opened text file using close() function
file.close()

# Print the final results using the final values 
# Of the line_count and word_count variables
print(f"\nTotal number of lines in the given file: {line_count}")
print(f"\nTotal number of words in the given file: {word_count}")

Output:

Total number of lines in the given file: 2

Total number of words in the given file: 13

Conclusion

In this tutorial, we have learned the following things:

  • How to create a text file using Python?
  • How to read the content of a text file in Python?
  • Algorithm to count the number of lines and words in a given text file.
  • How to count the number of lines and words in a text file using Python?

Hope you are clear and are ready to perform these tasks on your own. Thank you and stay tuned with us for more such Python tutorials.