Count the words inside the file
Write a program to read a text file, count the number of words, and write the number of words in a new file.
 
Write a program to read a text file, count the number of words, and write the number of words in a new file.
from pathlib import Path
path = rf"{input("Enter the path : ")}"
words = Path(path).read_text()
total = 0
for x in words:
    if x == " " or x == "." or x == "!" or x == "?":
        total += 1
print(f"The words count is : {total}"))
with open('input.txt','r') as file:
    text = file.read()
    words = text.split()
    word_count = len(words)
    with open('output.txt','w') as file:
        file.write(f"{word_count}")
print(word_count) 
def count_words_in_file(input_filename, output_filename):
    try:
        with open(input_filename, 'r', encoding='utf-8') as file:
            text = file.read()
        # Word count (split text based on spaces)
        words = text.split()
        word_count = len(words)
        # Write the result in the output file
        with open(output_filename, 'w', encoding='utf-8') as file:
            file.write(f"تعداد کلمات فایل '{input_filename}': {word_count}\n")
        print(f"تعداد کلمات: {word_count} در فایل '{output_filename}' ذخیره شد.")
    except FileNotFoundError:
        print(f"فایل '{input_filename}' پیدا نشد.")
    except Exception as e:
        print(f"خطا رخ داد: {e}")
def count_words(input_file, output_file):
    with open(input_file, 'r', encoding='utf-8') as f:
        text = f.read()
        word_count = len(text.split())
    with open(output_file, 'w', encoding='utf-8') as f:
        f.write(f'Number of words: {word_count}')
count_words('input.txt', 'output.txt')
Submitting answers is currently unavailable.
You must be logged in to access this section.
Login/Sign up If you don’t understand the exercise or can’t solve it for any reason, that’s completely
                    normal—don’t worry 😊 
 Try checking out easier exercises and reviewing different answers
                    submitted by others. Gradually, you can move on to more challenging exercises. Also, your answer
                    might be correct even if it’s different from others.