0

I have a file with the following content.

1
2
3

Now I want to write 4,5 and 6 so that the file content will be like below

1
2
3
4
5
6

Instead of writing 4,5 and 6 by doing file.write("4" + '\n'), file.write("5" + '\n'), file.write("6" + '\n'), how can I write all those last three number with just calling file.write command only once?

Update: I do not know in advance how many number I will be adding to the file. Numbers that will be added are stored in a giant list.

Zip
  • 5,372
  • 9
  • 28
  • 39

4 Answers4

2

You can do this:

file.write("%s \n %s \n %s \n" % (string1, string2, string3))

I'm assuming the strings you want to write are actually more complicated that a single number.

Update:

Since you don't know all the content you're writing ahead of time, you can do this:

stringToWrite = ""
for x in listOfNumbers:
    stringToWrite += x + "/n"

file.write(stringToWrite)
JRodge01
  • 280
  • 1
  • 7
  • Zip: [This answer](http://stackoverflow.com/a/20187027/355230) to a possibly related question might also be of interest. – martineau Jul 18 '15 at 20:29
1

Assuming your strings don't end in newlines:

file.write('\n'.join(strings) + '\n')

If they do:

file.write(''.join(strings))

strings can be a list or tuple of string values, or anything else that's iterable containing string values.

martineau
  • 119,623
  • 25
  • 170
  • 301
0

Don't forget newline is just another character:

file.write("4\n5\n6\n")
Lawrence H
  • 467
  • 4
  • 10
0

I'm assuming you have '4', '5' and '6' as separate variables. If so, try this:

x='4'
y='5'
z='6'
file.write('\n'.join([x, y, z]) + '\n)
Fernando Matsumoto
  • 2,697
  • 1
  • 18
  • 24