Hi everyone, I am a beginner in python, and I would really appreciate if someone could help me with this.

Basically I am trying to write a program where I will be importing a file that has a lot of numbers in many lines, there are also some blank spaces. Now how do I count the number of items? So far I only got this:

import string

def main():

    fname = raw_input ("Enter filename:")
    
    infile = open(fname,"r")


    data = infile.read()

    items = len(open(fname).readlines())

   

    print items, "number of items."

main()

now the only problem it is also counting the number of blank spaces. How do I make it so it only counts the number of items but not the blank spaces between the items?

note: move from starting python where it violated the rules

Dani AI

Generated

Short answer: skip blank lines (and whitespace-only lines) before counting. As suggested, call strip() and test that the stripped line is non-empty. Prefer iterating the file with a context manager so the file is closed automatically and large files are not loaded into memory.

# count non-empty lines (one item per line)
with open('data.txt', 'r') as f:
    items = sum(1 for line in f if line.strip())
print(items, "items")

If a line can contain several numbers (items separated by spaces/tabs), split each line and test tokens for numeric conversion so non-numeric tokens are ignored:

# count numeric tokens anywhere in the file
count = 0
with open('data.txt', 'r') as f:
    for line in f:
        for token in line.split():
            try:
                float(token)
            except ValueError:
                continue
            count += 1
print(count, "numbers")

Notes and troubleshooting: readlines() (as suggested by ) works but loads the whole file into memory; prefer iteration for large files. Reading the file twice (for example calling file.read() and then iterating file again) will fail because the file pointer is at EOF — this is the issue in 's snippet; also always call file.close() or, better, use with open(...). Counting '\n' (as in 's approach) can miscount if the final line lacks a trailing newline. If comments or non-numeric tokens should be ignored, filter them explicitly. Use try/except around file open for missing files, and choose int() vs float() parsing depending on expected input.

Choice depends on what “item” means: use the non-empty-line pattern for one value per line, and token parsing when lines may hold multiple values.

Recommended Answers

All 4 Replies

Wouldn't be something like this? :

def main():
    fname = raw_input ("Enter filename:")
    infile = open(fname,"r")

    data = infile.readlines()
    infile.close()

    items = len(data)
    print items, "number of items."

main()

You should add a try:/except: because the filename the user might be trying might not exist.

You have to strip() each line to get rid of spaces and newlines, and then test for length greater than zero. That will skip any lines with spaces only.

fname= input("input a file name :")
file = open(fname,"r")
sentence = file.read()

count = 0 
print ("This program calculates the number of words ")
words = sentence.split()
characters = len(sentence)
wordCount = len(words)

for line in file.read().split('\n'):
    count += 1

print ("The total word count is:", wordCount)
print ("The total characters is:", characters)
print ("The total number of line is:", count)


file.close

A simplified version could be ...

''' text_analyze101.py
a simple way to analyze text
'''

text = '''\
A dad is on his way home a bit late from the office when he realizes
that it's his daughter's birthday and he has not bought her a gift.
So he stops at a toy store to buy his daughter a Barbie doll.  Inside
the store he sees a Barbie display and asks the salesgirl how much the
dolls are.

The salesgirl responds:
"Oh, we have
Gymnasium Barbie at $19.95
Volleyball Barbie at $19.95
Shopping Barbie at $19.95
Surfer Barbie at $19.95
Disco Barbie at $19.95
and Divorced Barbie at $299.99!"

Shocked, the man asks, "Why is Divorced Barbie $299.95 when all the other
Barbies are $19.95?"

The salesgirl responds:
"Sir, Divorced Barbie comes with:
Ken's Car
Ken's House
Ken's Boat
Ken's Furniture
Ken's Jewelery
Ken's Money
Ken's Computer
and Ken's Best Friend.!"'''

print("Number of lines in text  = {}".format(text.count('\n'))) # newline
word_list = text.split()
print("Number of words in text  = {}".format(len(word_list)))
print("Number of spaces in text = {}".format(text.count(" ")))
print("Number of characters     = {}".format(len(text)))

''' result ...
Number of lines in text  = 27
Number of words in text  = 133
Number of spaces in text = 109
Number of characters     = 758
'''
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.