简体   繁体   中英

python output data type confusion

Hi all this is the code I am trying to run. I am not a computer scientist and I know this is an easy answer I just do not have the tools to answer it. I am trying to get this list printed to a text file. It works if I print to screen. The error I get is this: "TypeError: expected a character buffer object"

here is the code

input = open('Tyger.txt', 'r')
text = input.read()
wordlist = text.split()

output_file = open ('FrequencyList.txt','w')
wordfreq = [wordlist.count(p) for p in wordlist]

#Pair words with corresponding frequency

dictionary = dict(zip(wordlist,wordfreq))

#Sort by inverse Frequency and print

aux = [(dictionary[key], key) for key in dictionary]
aux.sort()
aux.reverse()

for a in aux: output_file.write(a)

Thanks!

As I said in the comments above, change output_file.write(a) to output_file.write(str(a)) . When you print something, Python attempts to do an implicit string conversion of whatever you are printing. That is why print ing a tuple (as you are doing here) works. file.write() does no implicit conversion, so you have to covert it yourself with str() .

As noted in the comments to this answer, you probably need to call .close() on the file.

you can write your code like:

input = open('tyger.txt','r').read().split()
......
.........
............
for a in aux:
    output_file.write(str(a))
    output_file.close()

you must close() a file what you have opened to write,otherwise you won't be able to use the file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM