Skip to content

Instantly share code, notes, and snippets.

@ostechnix
Last active August 8, 2024 13:57
Show Gist options
  • Save ostechnix/043da8e7ab710e3be233ea4f2f706a1e to your computer and use it in GitHub Desktop.
Save ostechnix/043da8e7ab710e3be233ea4f2f706a1e to your computer and use it in GitHub Desktop.
Txtcwcount - A Simple Python Script to Count Characters and Words in a Plain Text File.
#!/usr/bin/env python
# ------------------------------------------------------------------
# Script Name: txtcwcount.py
# Description: A Python Script to Count Characters and Words
# in a Plain Text File.
# Website: https://gist.github.com/ostechnix
# Version: 1.0
# Usage: python txtcwcount.py filename
# ------------------------------------------------------------------
import sys
def count_words_chars(file_path):
with open(file_path, 'r') as file:
contents = file.read()
word_count = len(contents.split())
char_count = len(contents)
return word_count, char_count
def main():
if len(sys.argv) < 2:
print("Usage: python file_counter.py <file_path>")
return
file_path = sys.argv[1]
word_count, char_count = count_words_chars(file_path)
print("="*50)
print(f"File: {file_path}")
print(f"Character Count: {char_count}")
print(f"Word Count: {word_count}")
print("="*50)
if __name__ == "__main__":
main()
@ostechnix
Copy link
Author

Count Characters and Words in Text Files with Python

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment