0

Apologies, I am new to Python.

I am trying to import a list of products from a file in this format:

02154367, "Item 1", 1.45

38418495, "Item 2", 0.6

82530174, "Item 3", 0.95

and I need them in python in this format:

[[02154367,"Item 1",1.45],[38418495,"Item 2",0.6],[82530174,"Item 3",0.95]]

Any advice would be greatly appreciated :)

Community
  • 1
  • 1
  • csv module will do exactly that for you. Look at the documentation (except for the int/float => string bit, and integers cannot be represented with leading 0!) – Jean-François Fabre Dec 08 '16 at 14:30
  • Sure... Read the file, parse the file line by line, store the line in a list, store that list in a master list, read the next line, and repeat with a loop – MooingRawr Dec 08 '16 at 14:30
  • Use the `csv` module. https://docs.python.org/3/library/csv.html#csv.reader – Patrick Haugh Dec 08 '16 at 14:30

1 Answers1

-1

You can read the CSV files with pandas read_csv function. This method creates a dataframe which is an appropriate structure for data processing. But for your desired format, you can transform it to the list of lists.

import pandas as pd

df = pd.read_csv('file.csv', header=None)
data = df.values.tolist()
print data
# [[2154367L, ' "Item 1"', 1.45], [38418495L, ' "Item 2"', 0.6], [82530174L, ' "Item 3"', 0.95]]
amin
  • 1,413
  • 14
  • 24
  • This is not a problem for `pandas`. There's no reason to start whipping out the big data tools to do file I/O – Patrick Haugh Dec 08 '16 at 14:37
  • Thanks for the reply, but as I'm in school I can't download other modules. Is there any way I can do this with the 'csv' module? The documentation has confused me a bit. Thanks. – jbblackett Dec 08 '16 at 14:38
  • you can check http://stackoverflow.com/questions/19838380/building-list-of-lists-from-csv-file. – amin Dec 08 '16 at 14:40
  • 1
    @PatrickHaugh Perfectly fine to do that. Read this: http://stackoverflow.com/help/how-to-answer _"Make sure your answer provides that – or a viable alternative."_ – Mohammad Yusuf Dec 08 '16 at 14:50
  • @PatrickHaugh There is no evidence that the problem is a toy one. – amin Dec 08 '16 at 14:59