user2912389
user2912389

Reputation: 357

Import csv as list of list in python 3.3

i hav a list of list with 2 strings and 1 integer

list_of_ee = [["a","m",15],["w","p",34]]

i export this to csv file using this code.

import csv

myfile = open("pppp.csv", 'wb')
with open("pppp.csv", "w",newline='') as myfile:
    wr = csv.writer(myfile, quoting=csv.QUOTE_NONE)
    wr.writerows(list_of_ee)

result was

a m 15
w p 34

and i export that using this code

data = csv.reader(open('pppp.csv','r', newline=''))
data = list(data)
print(data)

and the result was

[['a', 'm', '15'], ['w', 'p', '34']]

but I want to import this results same as it was (as list of list and with 2 str and 1 integer)(when my program restart)in list_of_ee and I want to add them to list_of_ee (becoz when program starts there's no data in list_of_ee .

Upvotes: 0

Views: 508

Answers (2)

steveha
steveha

Reputation: 76735

If you use CSV, you get strings. See the documentation: http://docs.python.org/2/library/csv.html#module-contents

"No automatic data type conversion is performed."

@hcwhsa pointed you to an answer that shows how to use ast.literal_eval() to guess at the types. It's not too hard:

import ast
import csv

def convert_type(s):
    try:
        return ast.literal_eval(s)
    except (ValueError, SyntaxError):
        return s

def convert_csv_row(lst):
    return [convert_type(x) for x in lst]

data = csv.reader(open('pppp.csv','r', newline=''))
converted = [convert_csv_row(row) for row in data]
print(converted)

But really, why are you even using CSV if you want to preserve the types? Unless you are exporting data to a spreadsheet or something, I suggest you use JSON format.

import json

list_of_ee = [["a","m",15],["w","p",34]]

with open("test.json", "wt") as f:
    f.write(json.dumps(list_of_ee))

with open("test.json", "rt") as f:
    s = f.read()
    lst = json.loads(s)

print(lst)
assert list_of_ee == lst

JSON is a great way to export data to other programs.

But if you are just trying to save data for your own Python programs, it's even easier: just use pickle. http://docs.python.org/2/library/pickle.html

import pickle

list_of_ee = [["a","m",15],["w","p",34]]

with open("test.pickle", "wb") as f:
    f.write(pickle.dumps(list_of_ee))

with open("test.pickle", "rb") as f:
    bytes_data = f.read()
    lst = pickle.loads(bytes_data)

print(lst)
assert list_of_ee == lst

With pickle you need to write and read the file in binary mode, not text mode. Also with pickle you can save pretty much any Python native type, not just the basic ones supported by JSON. But pretty much only Python programs read a pickle file.

Upvotes: 2

Christian Ternus
Christian Ternus

Reputation: 8492

There's no CSV-builtin way of doing what you're asking, since the CSV format has no notion of datatypes; that is, it doesn't distinguish between a string and an integer.

You could try doing something like this:

for lst in list_of_ee:
    for i,l in enumerate(lst):
        try:
            lst[i] = int(l)
        except:
            pass

to convert numerical elements of your sublists into integers.

Upvotes: 1

Related Questions