0

I am writing a Python program and I want to write my data to a file in such a way that there are sixteen values on each line. How do I do that, please?

Tim
  • 9,171
  • 33
  • 51
  • Can you give us examples of your source data, how you would like your output to look and finally what you have tried: [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) please. – figbeam Nov 04 '18 at 22:41

2 Answers2

0

You just have to add a character '\n' (new line character) every 16 elements. You can easily do this by iterating your data.

Woodstock94
  • 196
  • 10
0

You can use Python's list slicing. See here if you are unfamiliar. You essentially want a 'sliding window' 16 elements wide.

One solution:

# create list [1 ... 999] ... we will pretend this is your input data
data = range(1, 1000)

def write_data(filename, data, per_line=16):
    with open(filename, "w+") as f:
        # get number of lines
        iterations = (len(data) / per_line) + 1

        for i in range(0, iterations):
            # 0 on first iteration, 16 on second etc.
            start_index = i * per_line
            # 16 on first iteration, 32 on second etc.
            end_index = (i + 1) * per_line
            # iterate over data 16 elements at a time, from start_index to end_index
            line = [str(i) for i in data[start_index:end_index]]
            # write to file as comma seperated values
            f.write(", ".join(line) + " \n")

# call our function, we can specify a third argument if we wish to change amount per line
write_data("output.txt", data)
silber11
  • 26
  • 4