Skip to content

Instantly share code, notes, and snippets.

@mapi68
Last active March 11, 2024 07:29
Show Gist options
  • Save mapi68/9d0ba5bac483823c5e5337c7506f46c7 to your computer and use it in GitHub Desktop.
Save mapi68/9d0ba5bac483823c5e5337c7506f46c7 to your computer and use it in GitHub Desktop.
This Python script reads and analyzes the content of 'text.txt,' counting characters and lines. If the file doesn't exist, user input is used.
import os
# Specify the file name
file_name = "text.txt"
# Check if the file exists
if os.path.exists(file_name):
# Read the content of the file with explicit encoding (e.g., 'utf-8')
with open(file_name, "r", encoding="utf-8") as file:
content = file.read()
else:
# If the file doesn't exist, read from the console
print(f"The file {file_name} does not exist. Enter text below:")
content = input()
# Calculate the number of characters, including newline characters
character_count = len(content)
# Count the number of lines
line_count = (
content.count("\n") + 1
) # Adding 1 to count the last line if it doesn't end with a newline
# Print the result
print(f"The number of characters is: {character_count}")
print(f"The number of lines is: {line_count}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment