1

I am counting the number of occurrences of words in a list (called a_master). The words to search for and count are in dictionary.txt. The problem is, when I write the count to file, it comes out like this:

1Count cloud
19Count openstack
3 

And here is the code:

with open("dictionary.txt","r") as f:
for line in f:
    if a_master.count(line.strip()) !=0:
        file.write( "Count " + line + str((a_master).count(line.strip())))

As you can see, for some reason when it's outputting the number, it puts it on a new line and i have no idea why!

Cœur
  • 37,241
  • 25
  • 195
  • 267
Danny
  • 75
  • 1
  • 2
  • 8
  • possible duplicate of [Python file.write new line](http://stackoverflow.com/questions/9184107/python-file-write-new-line) – fedorqui Apr 23 '15 at 11:22

1 Answers1

1

Use .strip() on line.

Try this

with open("dictionary.txt","r") as f:
for line in f:
    if a_master.count(line.strip()) !=0:
        file.write( "Count " + line.strip() + str((a_master).count(line.strip())))
  • 1
    and more efficient to just do the operations once and set line=line.strip() and n=a_master.count(line) – paddyg Apr 23 '15 at 11:29