0

I have a python list as follows:

data = [1,2,3,4,5]

I want to write it in text file as follows:

1,2,3,4,5 ##as comma delineated.

I tried as:

with open ('data.txt', 'w') as fo:
   for d in data:
     fo.write(str(d) + '\n')

But it wrote data as follows:

1
2
3
4
5

How would you do it guys?

EDIT:

I will also have other lists obtained from for-loop, so all the one list i.e., 1,2,3,4,5 have to be adjusted in one line. In addition, I need faster performance.

0

5 Answers 5

7

It looks like you want a CSV (comma separated value) file as your output. You can use the CSV python module.

An example could look like:

import csv

data = [1,2,3,4,5]

with open('test.csv', 'w') as csvfile:
    writer = csv.writer(csvfile, delimiter=",")
    writer.writerow(data)
Sign up to request clarification or add additional context in comments.

Comments

7

You can use the join method

with open ('data.txt', 'w') as fo:
     fo.write(','.join(str(i) for i in data))

Comments

5

The simplest way is to convert the list to a joined string, then write:

str_data = ','.join(str(i) for i in data)
with open('data.txt', 'w') as fo:
    fo.write(str_data)

In case if the list is too long to convert it all to the string:

with open('data.txt', 'w') as fo:
    for idx, item in enumerate(data):
        if idx:  # don't need a comma before the list
            fo.write(',')
        fo.write(item)

Update: that all said, aus_lacy's suggestion about CSV seems the best.

Comments

1
data = [1, 2, 3, 4, 5]
with open ('data.txt', 'w') as fo:
    fo.write(','.join([str(n) for n in data]))

Comments

0

A simple way

data=[1,2,3,4,5]
with open ('data.txt', 'w') as fo:
   for d in data:
      if d!=data[len(data)-1]:
         fo.write(str(d)+',')
      else:
         fo.write(str(d))

Not so simple one:

dat=','.join([str(t) for t in data])
fo.write(dat)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.