-5

So I am trying to open a new file, and write in to that file all the values of n.

for n in [4, 7, 8, 10, 6, 3, 5, 13]:
    if n > 5:
        print(n)
b = open('new', 'w')
b.write(n)

It writes the numbers in as a string and only writes in 13, the last n.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Ben
  • 25
  • 2
  • I think you're opening the file with `w`, meaning 'write', and you're overwriting previous writes you do to that file. Try `a` for append, I think. – Chris Sprague Jun 30 '16 at 14:03
  • 2
    Also you're doing it **outside the loop**, after it has completed. – jonrsharpe Jun 30 '16 at 14:03
  • 1
    Possible duplicate of [How do you append to a file in Python?](http://stackoverflow.com/questions/4706499/how-do-you-append-to-a-file-in-python) –  Jun 30 '16 at 14:04

2 Answers2

1

Modified code:

with open('new', 'w') as outfile:
    for n in [4, 7, 8, 10, 6, 3, 5, 13]:
        if n > 5:
            print(n)
            outfile.write(str(n))

or (Not recommended)

for n in [4, 7, 8, 10, 6, 3, 5, 13]:
    if n > 5:
        print(n)
        b = open('new', 'a') # append mode
        b.write(str(n))
        b.close()
Devi Prasad Khatua
  • 1,185
  • 3
  • 11
  • 23
-1

You are printing the last value only. So you are getting the result only 13.You have to write the value in the for loop.

b = open('new', 'w')
for n in [4, 7, 8, 10, 6, 3, 5, 13]:
    if n > 5:
        print(n)
        b.write(n)
SumanKalyan
  • 1,681
  • 14
  • 24