Home > Enterprise >  Python create file from list add empty line to the end
Python create file from list add empty line to the end

Time:12-21

I have to create the CVS file from the list, here is the code

data_list = ['1', '2' , '3', '4']
        with open("myfile.csv", "w", newline="") as output_file:
            for each_line in data_list:
                output_file.write(each_line   "\n")

I can understand "\n" breaks the line but when I open the file i see last line is EMPTY. this is how content looks like

1
2
3
4
  # empty line

Is there any way i can remove last empty line?

found the way to fix this.. but wanted to check if this is the right way

        data_list = ['1', '2' , '3', '4']
        with open( "mycvs.csv", "w") as output_file:
            counter = 0
            for each_line in data_list:
                if counter < len(data_list) -1:
                    output_file.write(each_line   "\n")
                else:
                    output_file.write(each_line)
                counter  = 1

CodePudding user response:

Loop to the second last element of the list and do the last element without the "\n"

with open("myfile.csv", "w", newline="") as output_file:
    for each_line in data_list[:-1]:
        output_file.write(each_line   "\n")
    output_file.write(data_list[-1])

CodePudding user response:

You can try this:

with open("myfile.csv", "w") as output_file:
    length = len(data_list)
    for i in range(length-1):
        output_file.write(data_list[i] "\n")
    output_file.write(data_list[length-1])

The output does not contain a new line in this case.

But as mentioned in this post, you shouldn't leave a file without a terminating \n in the last line.

  • Related