Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python create file from list add empty line to the end

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading