How to write multiple values to on a row to txt and avoid tuple?

Viewed 56

I would like to write three values on a row in my txt.

My function:

def write_txt(file_name: str, content: str) -> None:
    with open(file_name, "a") as text_file:
        text_file.write(content + "\n")

But when I insert multiple values into a content (as a tuple) like this: write_txt("myfile.txt",f"{int(value[0]),int(value[1]),int(value[2])}") I got this in my txt:

(594940819, 1, 0)
(594940820, 1, 1)
(594940822, 1, 1)

But desired output is this:

594940819,1,0
594940820,1,1
594940822,1,1

How can I do this without using multiple replace? Thanks

4 Answers

str.join is perfect for this, just make sure you convert everything in content to a string before joining:

>>> content = (594940819, 1, 0)
>>> content_str = map(str, content)
>>> line = ",".join(content_str) + "\n"
>>> print(line)
594940819,1,0

Instead of using tuple itself, you should have tried using join function on the tuple and a few other functions:

tupleToString = ",".join(map(str, yourTuple)) + "\n"

Note that, in order to pass the data to join function, you need to transform the element from int to str. We achieve this goal using a map function which transforms the value into a string then pass this map object to the join function.

{int(value[0]),int(value[1]),int(value[2])} is a tuple. You can rather pass the correct string representation:

f"{int(value[0])},{int(value[1])},{int(value[2])}"

The problem seems to be in your input:
write_txt("myfile.txt",f"{int(value[0]),int(value[1]),int(value[2])}") here you are passing the string f"{int(value[0]),int(value[1]),int(value[2])}" that evaluates as a tuple since you have put commas. Correct text: f"{int(value[0])},{int(value[1])},{int(value[2])}" Correct statement:

write_txt("myfile.txt",f"{int(value[0])},{int(value[1])},{int(value[2])}")
Related