Ronin
Ronin

Reputation: 2067

Print output in text file in Python - Newline issue

Hi I am having problem with print the output in a text file. Suppose, I have an array

A=[ [1,2,3],
[4,5,6],
[7,8,9] ]

I have the code :

       for i in A:
         for j in i:              
            print(j),
         print ""

it will print

      1 2 3
      4 5 6
      7 8 9

now I have the code to print the same output in a text file

    for i in A:
    for j in i:
        print >> file,j
        print(j),

    print ""
    print >> file,""

but this is not writing the same previous console output in the file. How can I write the same output ?? Thanks.

Upvotes: 0

Views: 115

Answers (1)

Rush
Rush

Reputation: 496

Could you try the below code? It should work as you want it to

A=[ [1,2,3],
    [4,5,6],
    [7,8,9] ]

f = open('myfile','w')

for i in A:
    for j in i:    
        print(j),
        f.write(str(j) + ' ')
    f.write("\n")

f.close()

Upvotes: 1

Related Questions