kieraaa1
kieraaa1

Reputation: 1

Reading a file AND printing the number of words

I have to write a code that reads a file and counts the number of words in the file.

So far I am able to either print the file or count the number of numbers but I am unable to print them both without the other one automatically cancelling out. My file:

This is a files
that
has different
lengths of lines 

My code:

file = open('file_lab.txt', 'rt')
print(file.read())

data = file.read()
words = data.split()

print('Number of words in text file:', len(words))

My output:

This is a files
that
has different
lengths of lines
Number of words in text file: 0

As you can see it prints out the word count as zero and if I were to take out "print(file.read())" it reads the number of words correctly but doesn't print out the file.

Upvotes: 0

Views: 35

Answers (1)

Loocid
Loocid

Reputation: 6441

When you call .read() it moves the read marker to the end of the file so when you call .read() again, you're already at the end.

Replace

print(file.read())
data = file.read()

with

data = file.read()
print(data)

So you're only reading the file once.

Upvotes: 2

Related Questions