user1478335
user1478335

Reputation: 1839

writing data to a file in a specific format using Python

I am trying to write numeric data from a function return in the format:

[1,2,3,4,5][10,11]
[6,7,8,9,10][13,14]
...

The problem is that I want the text file to be in the format:

1,2,3,4,5[::tab::]10,11
6,7,8,9,10[::tab::]13,14
...

At the moment I am using

with open(outfilename,'a') as outfile:
    outfile.writelines("%s%s\n"%(major,minor))

I would be thankful for help please. I am still totally confused by lists, reading and writing to text files, and achieving specific formatting of data. I always end up with unwanted [] or parentheses.

Upvotes: 1

Views: 3190

Answers (1)

Rubens
Rubens

Reputation: 14768

You can simply write strings using the elements from the list, joining each element with a ,, or the separator you want; then, print the lists using a \t between them.

with open(outfilename, 'at') as outfile:

    major = ",".join(str(i) for i in major)
    minor = ",".join(str(i) for i in minor)

    outfile.writelines("%s\t%s\n" % (major, minor))

The magic behind the following line is very simple, actually:

major = ",".join(str(i) for i in major)

Python offers a feature named list comprehension, that allows you to perform an action over the elements of a list with a very clear and straightforward syntax.

For example, if you have a list l = [1, 2, 3, 4, 5], you can run over the list, converting the elements from integers to strings, calling the method str():

do _something_ with _element_ foreach _element_ in list _l_
          str(element)           for       element in l

When you do this, each resultant string will be created at a time, and you have a generator in this statement:

(str(element) for element in l)

As the method join works by iterating on a list of elements, or receiving this elements from a generator, you can have:

delimiter = ","
delimiter.join(str(element) for element in l)

Hope it clarifies the operation above.

Upvotes: 1

Related Questions