Mengzhu Yan
Mengzhu Yan

Reputation: 37

How to save the output to txt file?

When I got the number of how many times of the words, I wanted to save the output to a txt file. But when I used the following code, only counts appeared in the output file. Anyone knows the problem here? Thank you very much!

My code: (part)

d = c.split() # make a string into a list of words
#print d
counts = Counter(d) # count the words 
print(counts)

import sys
sys.stdout = open("C:/Users/Administrator/Desktop/out.txt", "w")
print 'counts'

Upvotes: 2

Views: 228

Answers (4)

doru
doru

Reputation: 9110

import sys
from collections import Counter

c = "When I got the number of how many times of the words"
d = c.split() # make a string into a list of words
counts = Counter(d) # count the words 
sys.stdout = open("C:/Users/Administrator/Desktop/out.txt", "w")
print(str(len(d)) + ' words') #this shows the number of total words 
for i in counts:
    print(str(i), str(counts[i]) + ' counts')

With te result in out.txt

12 words
When 1 counts
got 1 counts
many 1 counts
times 1 counts
the 2 counts
words 1 counts
I 1 counts
number 1 counts
how 1 counts
of 2 counts     

Upvotes: 0

Wayne Werner
Wayne Werner

Reputation: 51787

Another, slightly nicer option, would be to use some of the newer Python features:

from __future__ import print_function

with open(r'c:\Users\Administrator\Desktop\out.txt', 'w') as f:
    d = c.split() # make a string into a list of words
    #print(d, file=f)
    counts = Counter(d) # count the words 
    print(counts, file=f)

    print('counts', file=f)

Alternatively, you could use the logging module:

import logging

logger = logging.getLogger('mylogger')
logger.addHandler(logging.FileHandler(filename=r'c:\Users\Administrator\Desktop\out.txt'))
logger.setLevel(logging.DEBUG)


wordlist = c.split()
logger.debug('Wordlist: %s', wordlist)

logger.debug('Counting words..')
counts = Counter(wordlist)
logger.debug('Counts: %s', counts)

As it appears you're on Windows, you can use the incredibly useful baretail application to watch your log as your program executes.

Upvotes: 0

Aida Paul
Aida Paul

Reputation: 2722

Working as intended as python is a dynamic language and everything as it was during runtime. So in order to capture everything you will have to redirect your stdout at the begging of your script.

import sys
sys.stdout = open("C:/Users/Administrator/Desktop/out.txt", "w")
d = c.split() # make a string into a list of words
#print d
counts = Counter(d) # count the words 
print(counts)

print 'counts'

Upvotes: 3

Ionut Hulub
Ionut Hulub

Reputation: 6326

import sys
d = c.split() # make a string into a list of words
#print d
counts = Counter(d) # count the words 
sys.stdout = open("C:/Users/Administrator/Desktop/out.txt", "w")
print(counts)
print 'counts'

print prints to stdout. You need to redirrect stdout to the file before printing the number of counts.

Upvotes: 0

Related Questions