0

I have a question about how to save a list as a CSV file in my way:

I have a large list with many columns:

ex. ['2020-03-01T21:46:56Z', '059d422b-9da1-4be4-836b-dca71e44ff24', '23.595858333333336', '37.95288666666667', '', '', '0', '80', 'PERIOXH', 0.0005636937949292874]

Although I don't want to save the last column : 0.0005636937949292874

How can I do it? Here is my code:

with open(save_file, 'w', newline='\n') as f:
        writer = csv.writer(f)
        writer.writerows(result_buffer)
1
  • 1
    if result_buffer is your list you can simply do result_buffer[:-1] to remove last element of the list Commented Aug 25, 2020 at 14:22

3 Answers 3

1

you can iterate over your list and remove the last item for each line:

with open(save_file, 'w', newline='\n') as lines:
    writer = csv.writer(f)
    for line in lines:
        writer.writerow(line[:-1])
Sign up to request clarification or add additional context in comments.

Comments

0

You can slice your list

    list = ['2020-03-01T21:46:56Z', '059d422b-9da1-4be4-836b-dca71e44ff24', '23.595858333333336', '37.95288666666667', '', '', '0', '80', 'PERIOXH', 0.0005636937949292874]
    print(list[0:-1])
    >>>['2020-03-01T21:46:56Z', '059d422b-9da1-4be4-836b-dca71e44ff24', '23.595858333333336', '37.95288666666667', '', '', '0', '80', 'PERIOXH']

Comments

0

I used slicing.

my_list = ['2020-03-01T21:46:56Z', '059d422b-9da1-4be4-836b-dca71e44ff24', 
'23.595858333333336', '37.95288666666667', '', '', '0', '80', 'PERIOXH', 
0.0005636937949292874]
import csv
with open('result.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerow(my_list[:-1])

Output:

2020-03-01T21:46:56Z,059d422b-9da1-4be4-836b-dca71e44ff24,23.595858333333336,37.95288666666667,,,0,80,PERIOXH

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.