0

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
8
  • what's the last element of data_list? Commented Dec 20, 2021 at 20:04
  • Don't include the /n at the end of the last line. Commented Dec 20, 2021 at 20:06
  • @timgeb I updated my question Commented Dec 20, 2021 at 20:06
  • 2
    keep it as is Commented Dec 20, 2021 at 20:07
  • 2
    Shouldn't this be a backslash \ ? Commented Dec 20, 2021 at 20:07

2 Answers 2

2

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])
Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

Thanks to @timgeb for linking me to that page.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.