in Python, how can i write from a text file with each word being a different element? -
i need use file in format:
product1,33,84 product2,18.50,72 product3,22,96
and need write elements list in format:
['product1', '33', '84', 'product2', '18.50', '72', 'product1', '22', '96']
however when writing code, closest was:
[['product1', '33', '84'], ['product2', '18.50', '72'], ['product1', '22', '96']]
using code:
for line in productlist.readlines(): line = line.replace(",", " ") line = line.strip("\n") line = line.split(" ") products.append(line)
how can either write element or merge these nested lists?
you're there. want products.extend(line)
instead of append
. extend
method adds each element of iterable (in case, line
) list (products
), instead of adding item list @ once, append
does. final code (condensed little) looks this:
for line in productlist.readlines(): line = line.replace(",", " ").strip("\n").split(" ") products.extend(line)
Comments
Post a Comment