To print the contents of a list as comma-separated text
What should I do?
["dog", "cat", "pig"]
I would like to write the following list in the text.
Dogs, cats, pigs
If you execute the code below,
str_li=["dog", "cat", "pig"]
with open('test.txt', 'w', encoding='utf-8') asf:
for x instr_li:
f.write(x)
Run Results (test.txt)
Dogs, cats, pigs
with open('test.txt', 'w', encoding='utf-8') asf:
for x instr_li:
Concatenated with new_x=", ".join(x)#join
f.write(new_x)
It looks like the following.
Dogs, piglets
The join returns the merged string, so you don't have to use for to extract the contents of the list.
str_li=["dog", "cat", "pig"]
f=open('test.txt', 'w', encoding='utf-8')
f.write(", ".join(str_li))
f.close()
If you want to use with to avoid forgetting to close the file,
with open('test.txt', 'w', encoding='utf-8') asf:
f.write(", ".join(str_li))
will be
It probably doesn't need to be looped, just create a pre-connected string and write it down.
example:
str_li=["dog", "cat", "pig"]
new_x=", ".join(str_li)
with open('test.txt', 'w', encoding='utf-8') asf:
f.write(new_x)
str_li=["dog", "cat", "pig"]
with open('test.txt', 'w', encoding='utf-8') asf:
print(*str_li, sep=',',', file=f)
Run Results
$cattest.txt
dogs, cats, pigs
Just in case, I added a numerical list.
str_li=['dog', 'cat', 'pig']
num_li = [1,2,3]
with open('test.txt', 'w', encoding='utf-8') asf:
f.write(','.join(str_li)+'\n')
f.write(','.join([str(x)for x in num_li]) + '\n')
with open('test.txt', 'r', encoding='utf-8') asf:
print(f.read(), end='')
Dogs, cats, pigs
1,2,3
© 2025 OneMinuteCode. All rights reserved.