Home > Net >  How to write lines to a file with the last line without linebreak?
How to write lines to a file with the last line without linebreak?

Time:07-05

I am writing a list of strings to a text file in Python for Windows 10.

What I tried at first is

with open('filename1.txt', 'w') as f:
    for line in list1:
        f.write(line)
        f.write('\n')

The problem is the output file has a linebreak at the last of the file.

The next thing I tried is

with open('filename1.txt', 'w') as f:
    for line in list1[:-1]:
        f.write(line)
        f.write('\n')
    f.write(list1[-1])

This works fine, but I believe there must be a more elegant way to achieve this. Is there a nice way to do this?

CodePudding user response:

This?

f.write('\n'.join(list1))

CodePudding user response:

Options include:

  • Wrap the code in a function, so that you only have to worry about this line-writing algorithm once. Of course, you're still slicing the list, which is memory-inefficient.
  • Join the strings with newlines ahead of time; '\n'.join(list1) will not have a trailing newline, so it implicitly solves the problem. This is also memory inefficient, since you create that string in memory.
  • Invert the logic - instead of putting a newline after each line but the last, we can put one before each line but the first. It's easier to know which line is first while we're iterating through them, than which is last; this way, we don't need to slice - we can use flag logic instead. Thus:
with open('filename1.txt', 'w') as f:
    started = False
    for line in list1:
        if started:
            f.write('\n')
        started = True
        f.write(line)

(Of course, I would still make a function for that.)

CodePudding user response:

Julien's answer is the simplest and most elegant, but it means creating the whole file output in memory. You didn't say whether that would be OK or not, so if it is, go for their solution.

If you want to avoid that temporary copy, I would use an explicit iterator to first print the initial line, and then output a newline before each subsequent line:

with open('filename1.txt', 'w') as f:
    my_iter = iter(list1)  
    f.write(next(my_iter, ''))
    for line in my_iter:
        f.write('\n')
        f.write(line)

It may not look like more elegant code, but it's avoiding any additional temporary copy of the list, before or after formatting.

CodePudding user response:

I think I understand, what do you mean by linebreak there is a way to avoid that

by using join or python himself

this is the slow way but it does the same like join

colors = ['red', 'green', 'blue', 'yellow']
output = ""
separator = ", " # replace it with new line "\n"
length = len(colors)
for color in range(length):
    print(color,length)
    if color == (length-1):
        output  = colors[color]
    else:
        output  = colors[color]   separator

f.write(output)

or

f.write(", ".join(colors)) # replace the string with new line "\n"

and the output will always be

red, green, blue, yellow
  • Related