Home > Software engineering >  write items from a list to a text file in different line
write items from a list to a text file in different line

Time:11-30

I'm trying to get user inputs a few times and then save those inputs to a list and after that write list items to a text file. the list would look like this with the inputs.

prog_input = [120,0,0,100,20,0,100,0,20]

I wrote this to a text file using:

txtfile1 = open("Input progression data.txt", "w ")
txtfile1.write(', '.join([str(item) for item in prog_input])  '\n')

This just print them in a line.()

The output I'm trying to get is(in the text file):

120,0,0
100,20,0
100,0,20

CodePudding user response:

prog_input is just a flattened list, so you need to group your items into chunks and then output to your file

prog_input = [120, 0, 0, 100, 20, 0, 100, 0, 20]
step = 3
with open("Input progression data.txt", "w ") as myfile:
    for chunk in [prog_input[n:n step] for n in range(0, len(prog_input), step)]:
        myfile.write(','.join(map(str, chunk))   '\n')

CodePudding user response:

You can use numpy.array_split to split your list into sub-lists of size 3 each:

import numpy as np

prog_input = [120,0,0,100,20,0,100,0,20]
with open("Input progression data.txt", "w") as outfile:
    outfile.write("\n".join([", ".join(map(str, chunk)) for chunk in np.array_split(prog_input, 3)]))

CodePudding user response:

Looks like you want 3 values per line. So...

F = "Input progression data.txt"
prog_input = [120,0,0,100,20,0,100,0,20]
with open(F, 'w') as outfile:
    for o in range(0, len(prog_input), 3):
        print(','.join(map(str, prog_input[o:o 3])), file=outfile)

CodePudding user response:

', '.join([str(item) for item in prog_input]

This loops over the entire list and joins all of the elements with comma delimiters. If you want the output to be something else, then you need to do this differently.

I suggest describing in words what you want to do. From your example, it appears that you first need to take the list and subdivide it into lists with three elements each. I leave writing code to do that as an exercise to the reader.

CodePudding user response:

Move the \n to the right location This:

', '.join([str(item) for item in prog_input])  '\n'

Should be :

',\n'.join([str(item) for item in prog_input])

Edit:

If you want only 3 elements on each line you can use:

',\n'.join([', '.join([str(j) for j in prog_input[i:i 3]]) for i in range(0, len(prog_input), 3)])
  • Related