How to write to a file in python without adding a new line except at certain place?

Question:

I want to write to a file without adding a new line at the iterations of a for loop except the last one.

Code:

items = ['1','2','3']
with open('file.txt', "w") as f:
        f.write('test' + 'n')
        for t in items:
         f.write(t + 'n')#i didnt know i could add the 'n'
        f.write('test' + 'n')#here for it to work
        for t in items:
         f.write(t + 'n')
        f.write('end')

Output in the file:

test
1
2
3
test
1
2
3
end

Output I want in the file:

test
123
test
123
end

I am new to python, so sorry for any inconstancies.

Asked By: Zen35X

||

Answers:

if you want the list to become a string follow this template

num = [‘1’, ‘2’, ‘3’]
str1 = ""

for i in num:
str1 += i

print(str1)

output:
123

Answered By: Drew Levine
items = ['1','2','3']
with open('file.txt', "w") as f:
        f.write('test' + 'n')
        for t in items:
         f.write(t)
        f.write('n'+'test' + 'n')
        for t in items:
         f.write(t)
        f.write('n'+'end')

This is code that should solve your issue

items = ['1', '2', '3']
with open('file.txt', 'w') as f:
    f.write('test n')
    for i in items:
        f.write(i)
    f.write('n')
    f.write('test n')
    for i in items:
        f.write(i)
    f.write('n')
    f.write('end')

Notice that you just want to iterate through the list items in the for loop, then add a separate write statement for the new line before the next ‘test’
Also it’s best to just use the escape character n for newline within the single quotes instead of attaching it with the ‘+’ symbol.

Answered By: CDJimmyJazznMe
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.