Write array to text file with max number of elements in each row

Viewed 307

I'm a beginner with python and I tried to solve my problem for many hours, without success.

My Problem: I have an array A with 12 elements an I want to write A to a text file.

A = [1, 2, 3, 4, 5, 6, 101, 102, 103, 104, 105, 106]

The maximum number of columns of the text file is 8. So my new file should look like this:

*Header...

1, 2, 3, 4, 5, 6, 101, 102,

103, 104, 105, 106

I couldn't find a solution where I can specify the max numbers of columns and set the delimiter as ,.

Can you help me with this problem?

5 Answers

The chunks function splits your array into chunks of size n (it's a generator function); Here we have decided n to be 8 as per the o/p

Now coming to the print function, it's a function that outputs to your console window whatever you say you want to print out in the first look. But if you will look at it's signature from the docs, you will find that it can take few args as well.

The function signature of print looks like print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False);

We focus on the file arg as by default it's sys.stdout i.e. write everything to console; So what we can do is just change it with an object with a write(string) method;

def chunks(lst, n):
    # Yield successive n-sized chunks from the list..
    for i in range(0, len(lst), n):
        yield lst[i:i + n]

with open('my_file.txt', 'w') as fp: 
    for my_chunk in chunks(l, n=8): # save them
        print(my_chunk, file=fp)

Here is a simple readable solution with comments to get the hang of parsing lists into a text file. If you are planning on using larger data sets or removing the delimiter at the end, I would recommend looking into using slicing or some variation of a caching algorithm to improve performance.

A = [1, 2, 3, 4, 5, 6, 101, 102, 103, 104, 105, 106]
with open("fout.txt", "w") as f:
    # set width in a variable
    width = 8
    # Loop through each element in the list k = key, i = element (numeric in this case)
    for k, i in enumerate(A):
        # check for every 8th entry using mod on index of list to print the new line character at the end
        if (k+1) % width == 0:
            f.write(str(i)+",\n")
        # otherwise just print the next element in the list followed by a comma (change to variable for a different delimiter)
        else:
            f.write(str(i)+", ")

You can slice each time n elements (according to the desired number of columns) from your list and write them to your output file.

For example:

A = [1, 2, 3, 4, 5, 6, 101, 102, 103, 104, 105, 106]
A = list(map(str, A))
cols = 8
start_index = 0
with open("output.txt", "w") as f:
    while start_index <= len(A) - 1:
        f.write(",".join(A[start_index:start_index + cols])+"\n")
        start_index += cols

How about itertools.zip_longest and iter to chunk the list:

from itertools import zip_longest

A = [1, 2, 3, 4, 5, 6, 101, 102, 103, 104, 105, 106]
a_iter = iter(A)

with open('fn.txt') as f:
    for n in zip_longest(*[a_iter]*8):
        f.write(', '.join(map(str, filter(None.__ne__, n))) + '\n')

Here is what you can do:

A = [1, 2, 3, 4, 5, 6, 101, 102, 103, 104, 105, 106]

with open("file.txt","w") as f:
    while len(A) > 8:
        f.write(', '.join([str(n) for n in A[:8]])+'\n')
        A = A[8:]
    f.write(', '.join([str(n) for n in A]))
Related