'How to write multiple values to on a row to txt and avoid tuple?
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
Solution 1:[1]
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
Solution 2:[2]
{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])}"
Solution 3:[3]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tzane |
| Solution 2 | nick |
| Solution 3 |
