'How not to add delimiter after last element
Im working on python code that reads and then updates lines in file and shows them in tabulate(before and after) but when it write data back to file, delimiter ":" is added after last element and that crashes tabulate form, how can i avoid this
with open ('hotel.txt', 'w') as file:
for i in list:
for j in i:
file.write(j+':')
file.write('\n')
error: Exception: Row has incorrect number of values, (actual) 8!=7 (expected)
Also: i cant change tabulate form because of assigment
Solution 1:[1]
It is conventional to use str.join
when combining strings separated by delimiters:
with open ('hotel.txt', 'w') as file:
for i in list:
file.write(":".join(i))
file.write('\n')
Solution 2:[2]
Ideally you would just use ":".join(...)
but this assumes you have a list (or other iterable) of strings. It fails if any item is not a string, but then again, so does file.write()
. You can use a list comprehension to stringify all items:
file.write(":".join(str(x) for x in item)
In cases where writing items is more involved, istead of writing the delimiter after each item and trying to avoid writing the last one, write the delimiter before each item and avoid writing the first one.
with open ('hotel.txt', 'w') as file:
for i in list:
delim = ""
for j in i:
file.write(delim + j)
delim = ":"
file.write('\n')
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 | Kevin |
Solution 2 |