0

I have an array called 'thelist' and it holds some numbers which I want to output to a file on the same line delimited with commas. I did this using:

thelist = [1,6,5,2,7]

thefile = open('test.txt', 'w')

name = "bob"

for item in thelist:
  thefile.write("%s,"%(item))

output:

1,6,5,2,7,

However, I want to be able to write the name and the array on the same line. So it'd look something similar to bob 1,6,5,2,7

I tried to use thefile.write("%s %s,"%(name,item)) but that unfortunately does not work. I tried to search for an answer but I didn't find a solution. Any ideas? Is this even possible?

2 Answers 2

1

precede the for-loop by thefile.write("%s ", name)

Your lat lines would look like this:

thefile.write("%s " % name)
for item in thelist:
  thefile.write("%s,"% item)

In addition, to remove the annoying comma at the end, you can consider

outStr = ",".join(map(str, thelist))
thefile.write("%s %s" %(name, outStr))
Sign up to request clarification or add additional context in comments.

1 Comment

Your solution gave me a TypeError: write() takes exactly 2 positional arguments (3 given) error which I managed to fix by doing thefile.write("%s " %name) and thefile.write("%s,"% item). This gave me bob 1,6,5,2,7 which also removed the comma at the end without me adding the extra code.
0
thefile.write("{n} {l}".format(n=name, l=",".join(str(i) for i in theList)))

Comments

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.