0

Im trying to count the amount of words in a text document then write the total back to the .txt

here is how far i've got

words = 0
   f = open("count.txt", 'r+')

for wordcount in f.readline().split(" "):
   words += 1


print('number of words ')
print(words)


f.write("number of words ")
f.write(words)
f.close()

I get this error

TypeError: expected a character buffer object

Where am I going wrong?

i feel that f.write(words) isn't the correct way to write the total to the txt?

Tom HRM
  • 3
  • 3

4 Answers4

2

file.write accepts only a text buffer, so you need to cast words into a string first before writing it to a file:

f.write(str(words))
blhsing
  • 91,368
  • 6
  • 71
  • 106
2

You must convert words to a string before being able to write it into the file.

with open("count.txt", "r+") as f:
    words = len(f.read().split())
    print('number of words ')
    print(words)

    f.write("number of words ")
    f.write(str(words))

Moreover:

readlinereads only one line. Use readto read the whole file.

use lento count the size of a list, inside of counting it by yourself

use withto ensure that the file will be closed

Gelineau
  • 2,031
  • 4
  • 20
  • 30
1

f.write requires a string as its argument, unlike print, which will take any number of objects of any kind, and automatically convert them all into strings for you, and join them up with configurable separators and a configurable ending, and so on.

In other words, print is clever and friendly; write is a low-level function. So, to make this work with write, you have to do the conversion manually.

f.write(str(words))

But you can also just use print instead of calling f.write:

print(words, file=f)

Notice that this doesn't do quite the same thing. When you call print, by default, it puts a newline at the end. So, this code:

print('number of words ')
print(words)

… will print out two separate lines:

number of words
3

And likewise, this code:

print('number of words ', file=f)
print(words, file=f)

… will add the same two separate lines to the file.

abarnert
  • 354,177
  • 51
  • 601
  • 671
1

Words has to be converted to string. File.write() is what is actually going to write it.

Your new code:

f.write("number of words ")
f.write(str(words))
Arturo
  • 3,254
  • 2
  • 22
  • 61