-1

I need to write an array of integers into a text file, but the formatted solution is adding the comma after each item and I'd like to avoid the last one.

The code looks like this:

        with open(name, 'a+') as f:
           line = ['FOO ', description, '|Bar|']
           f.writelines(line)
           f.writelines("%d," % item for item in values)
           f.writelines('\n')

Each line starts with a small description of what the array to follow contains, and then a list of integers. New lines are added in the loop as they become available.

The output I get looks something like this:

FOO description|Bar|274,549,549,824,824,824,824,824,794,765,765,736,736,736,736,736,

And I would like to have it look like this, without the last comma:

FOO description|Bar|274,549,549,824,824,824,824,824,794,765,765,736,736,736,736,736

I was unable to find a solution that would work with the writelines() and I need to avoid lengthy processing in additional loops.

TeilaRei
  • 577
  • 1
  • 6
  • 22

4 Answers4

9

Use join:

f.writelines(",".join(map(str,values)))

Note that values is first mapped to a list of strings, instead of numbers, with map.

trincot
  • 317,000
  • 35
  • 244
  • 286
  • This would work, but I need to keep numbers without converting them to strings – TeilaRei Aug 28 '17 at 14:42
  • Content written to a file is always written as a string, you convert it to string yourself with the `%` operator, and the desired output you have at the end of your question is a string. So I must ask: What do you mean? – trincot Aug 28 '17 at 14:44
  • That is a good point, for some reason I've been unaware of that transformation. I guess I was looking for a way to actually preserve the original type of the data, but it doesn't seem to be possible with the text file. – TeilaRei Aug 28 '17 at 14:51
1

You can slice it with using below example. It will always delete last character.

line = ['FOO ', description, '|Bar|']
line = line[:-1]
f.writelines(line)
Gokturk
  • 47
  • 1
  • 7
1

Slicing is the best approach and works well for every situation atleast in your case.

    f.writelines(line[:-1])
Chetan_Vasudevan
  • 2,414
  • 1
  • 13
  • 34
0

You can use print function here.

print(*values,sep=',',file=f)

If you are using python2 please import print function.

from __future__ import print_function
Abhijith Asokan
  • 1,865
  • 10
  • 14