简体   繁体   中英

in Python, how can i write from a text file with each word being a different element?

i need to use a file in the format:

product1,33,84
product2,18.50,72
product3,22,96

and need to write the elements to a list in the format:

['product1', '33', '84', 'product2', '18.50', '72', 'product1', '22', '96']

However when writing the code, the closest i could get was:

[['product1', '33', '84'], ['product2', '18.50', '72'], ['product1', '22', '96']]

using the code:

for line in productList.readlines():
    line = line.replace(",", " ")
    line = line.strip("\n")
    line = line.split(" ")
    products.append(line)

how can i either write by element or merge these nested lists?

You're almost there. You just want products.extend(line) instead of append . The extend method adds each element of the iterable (in this case, line ) to the list ( products ), instead of adding the item to the list all at once, which is what append does. So your final code (condensed a little) looks like this:

for line in productList.readlines():
    line = line.replace(",", " ").strip("\n").split(" ")
    products.extend(line)
>>> import csv
>>> from itertools import chain
>>> with open('data.csv') as f:
        print list(chain.from_iterable(csv.reader(f)))


['product1', '33', '84', 'product2', '18.50', '72', 'product3', '22', '96']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM