user3078840
user3078840

Reputation: 45

Python - writing multiple lists to file

I'm trying to write my output to a new file. The required output is 4 rows with n number of columns. It works fine when printing in the terminal, however as soon as I try to write the output to a file, it all prints on one line.

This is the code that I have which works until I print to file. I have no idea why the output isn't the same. Can anyone explain why it is different please and how can I go about correcting this? (sorry i'm a newbie so simple terms would be helpful!) Any help is appreciated thanks!

with open("file.txt", "w") as p:
pwm = f.readlines()
lis=[x.split() for x in pwm]
for x in zip(*lis):
    pwm = "\t".join(x)
    print str(pwm) # this prints in required format
    p.write(str(pwm)) # this prints all on one line

Required output:

0.224   0.128   0.536   0.009   0.007   0.085   0.013   0.097   0.058
0.339   0.152   0.136   0.002   0.002   0.009   0.876   0.031   0.829
0.250   0.421   0.299   0.004   0.065   0.845   0.027   0.834   0.007   
0.186   0.299   0.029   0.985   0.926   0.061   0.084   0.038   0.106

File output:

    0.224   0.128   0.536   0.009   0.007   0.085   0.013   0.097   0.058    0.339  0.152   0.136   0.002   0.002   0.009   0.876   0.031   0.829 etc...

Upvotes: 1

Views: 2324

Answers (3)

randomusername
randomusername

Reputation: 8105

Use the following:

p.writelines(str(pwm))

Upvotes: 2

merlin2011
merlin2011

Reputation: 75639

You can either write a newline explicitly or use print with a file redirection.

p.write(str(pwm) + "\n")

print >> p, pwm

Upvotes: 0

user2555451
user2555451

Reputation:

The write method of a file object just adds text to the end of the file. If you want to have each row on its own line, you need to add a newline to the end of the string:

p.write(str(pwm) + "\n")

You do not have to do this with print because it does this for you implicitly.

Upvotes: 1

Related Questions