I have a 1D array e.g. arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, ...]
of arbitrary length.
How do I print this to a text file (with integers/floats separated by spaces) so that every 7 elements are printed on the same line in the text file?
So I want the text file to look like this:
Line 1:1 2 3 4 5 6 7
Line 2:8 9 10 11 12 13 14
In Python, think "generator" !
result
And if you want to parameterize the number of numbers in each line, create a generator function:
You can chunk a sequence using this
zip
idiom:You can then compose an iterator for
writelines
:Finally use it:
Your question can be broken down into 3 parts:
Dividing a list of arbitrary size into chunks of a specific length
Using the
grouper
method as described in this answer:you can easily split a list of arbitrary length to chunks of a desired length. For example:
Printing a list of ints/floats using a space as delimiter
The standard way to join a list into a string is to use
string.join()
. However, that only works for lists of strings so we'll need to first convert each element into its string representation. Here's one way:Using this method in the previous example, we get:
That's pretty much the output you want. Now all we need to do is write that to a file.
Writing to a file
For details, see Reading and Writing Files.
you could do this:
here every 7 items a new line is appended... output looks like this:
hope that helps!
or you could do: