Jessie
Jessie

Reputation: 31

Python writing to file per character instead of per string

Suppose I have K and V. K contains a tuple

('String1', 'String2')

while V is a floating-point number

0.00324

What I'm trying to do is to write both into a text file like this:

('String1', 'String2') 0.00324

or

String1 String2 0.00324

My code is this:

for k,v in bigrams_frequency.items():
    number_unigrams = vocabulary.count(k[0])
    if number_unigrams == 0:
        continue;
    v = v / number_unigrams
    print(k,v)
    f2.write('\n'.join('%s %s' % (k,v)))

However, when I open the text file, the output looks like this:

(
'
S
t
r
i
n
g
1
.
.
.

What could be causing Python to print like this? How do I fix this?

Upvotes: 0

Views: 93

Answers (4)

WhatsThePoint
WhatsThePoint

Reputation: 3635

As discussed in the comments here is the code;

K=("string1","string2")
V=0.00324
file = open("test.txt","a")
file.write("{} {}".format(K,V))
file.close()

and it produces this output the file which you specified as a desired output in your question;

('string1', 'string2') 0.00324

you can also use a with statement when writing to files because a with statement automatically closes the file so you dont need to explicitly close it so for your example it will be;

with open("test","a") as file:
    file.write("{} {}".format(K,V))

just dont forget to indent where you need the file because as soon as it isnt indented anymore the file will close

Upvotes: 1

EriktheRed
EriktheRed

Reputation: 584

The problem lies here - f2.write('\n'.join('%s %s' % (k,v))).
The join method expects an iterable (like a list) in the parameters. When you give it the string 'String1 String2 Float', it 'joins' every two letters with a new line.
It seems all that you want to do is write every entry in a new line (not every letter!), so replace the line with something like f2.write('{} {}\n'.format(k, v))
If you haven't come across format yet, read up about it here.

Upvotes: 0

Ahasanul Haque
Ahasanul Haque

Reputation: 11134

You can do:

for k,v in bigrams_frequency.items():
    # Other code
    f2.write('{}{}\n'.format(join(k),v) )

And, it will be just fine.

Upvotes: 0

JeffQ
JeffQ

Reputation: 104

you have a wrong understanding of str.join(xx) function. This function "return a string which is concatenation of the string in the iterable xx". You can use str.format() instead.

Upvotes: 0

Related Questions