-2

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.

Zen35X
  • 76
  • 2
  • 10

3 Answers3

1
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')
1

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.

0

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