What i'm trying to do is writing Program that print the number of newlines,words and characters in counted file by python

I'm lost and i do not how should i do it?

that what i got so far

infilename = input("Enter the name of the file:")

infile = open ( infilename ,'r')

for line in infile:
    line = line.split()



print (line)

Dani AI

Generated

Your original loop ends up printing only the last processed item because print is outside the for loop. To get totals you need counters that are updated inside the loop (or do one-pass processing of the whole file). Also be explicit about what you mean by "characters" vs "bytes": bytes = raw file size (depends on encoding and CR/LF), characters = decoded text code units (len on a Python string), and "words" depends on how you tokenize (simple whitespace split vs a regex/tokenizer that handles punctuation and contractions).

A robust, memory-friendly approach:

  • For bytes use the filesystem size (fast and exact).
  • For lines and characters read text with an explicit encoding and accumulate lengths.
  • For words use a Unicode-aware regex if you want to avoid counting punctuation as words.

Example (different approach from prior posts):

import os, re

fname = input("Filename: ")
bytes_ = os.path.getsize(fname)

word_re = re.compile(r"\b[\w'-]+\b")   # simple Unicode-friendly tokener
lines = 0
chars = 0
words = 0

with open(fname, 'r', encoding='utf-8', errors='replace') as f:
    for lines, line in enumerate(f, 1):
        chars += len(line)              # decoded code units
        words += len(word_re.findall(line))

print("Lines:", lines)
print("Characters (code units):", chars)
print("Words:", words)
print("Bytes (file size):", bytes_)

Notes and troubleshooting: ’s per-line loop and ’s read-all methods both work; prefer streaming (above) for large files. ’s comment that “a character usually takes one byte” is only true for single-byte encodings (like ASCII); with UTF-8 many characters use multiple bytes. If you need grapheme-aware character counts (what a human thinks of as characters) consider a specialized library.

Recommended Answers

All 6 Replies

What is a counted file?
Please provide a testcase.

For example you can count newlines and characters like this:

infilename = input("Enter the name of the file:")
count_newlines=0
count_chars=0
with open (infilename ,'r') as infile:
    for line in infile:
        count_newlines+=1
        count_chars+=len(line)

print(count_newlines)
print(count_chars)

thank u
how can i count the bytes in file ?

sorry
how can i count the words in file ?

You split the line with space.
count_words+=len(line.split(" "))

A character usually takes up one byte.

You could also follow this approach ...

infilename = input("Enter the name of the file: ")

with open (infilename ,'r') as infile:
    data = infile.read()
    count_newlines = data.count('\n')
    count_chars = len(data)
    count_words = len(data.split())


print("Lines = {}".format(count_newlines))
print("Characters/bytes = {}".format(count_chars))
print("Words = {}".format(count_words))
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.