Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load data from a .csv file without importing the .csv module/library

Tags:

python

csv

def loadfunc(filestr):
listoftuples = []
listofnumbers = []
tupleinlist = []
with open(filestr, 'r') as file:
    for line in file:
        for item in line:
            if item.isdigit():
                listofnumbers.append(float(item))
            else:
                word = item
tupleinlist.append(word)
tupleinlist.append(listofnumbers)
listoftuples.append(tuple(tupleinlist))
return listoftuples
print(listoftuples)

Above is my code. So the requirement is to load data from a .csv file and into a list of tuples. The data in the file is something like:

 - apple    23.2    24.3    25.6
 - banana   22.1    20.0    19.9

Withing each tuple in the list it has to be (word, listoffloats) so the list would look like:

[(apple, [23.2, 24.3, 25.6]), (banana, [22.1, 20.0, 219.9])]

But with my code it screws this up and doesn't return it because when it iterates over "item" in each "line", it iterates over each character (like ., a, p, p, l, e) rather than item being things like apple, 23.2, etc.

Help please I don't know how to fix this and no it is not allowed to use csv libraries/modules for this tutorial.

like image 978
jb3navides Avatar asked Sep 01 '15 09:09

jb3navides


People also ask

What is the proper way to load a CSV file using?

On the Data tab, in the Get & Transform Data group, click From Text/CSV. In the Import Data dialog box, locate and double-click the text file that you want to import, and click Import. In the preview dialog box, you have several options: Select Load if you want to load the data directly to a new worksheet.

Which library is used to load a CSV file?

The Python csv library will work for most cases. If your work requires lots of data or numerical analysis, the pandas library has CSV parsing capabilities as well, which should handle the rest. In this article, you'll learn how to read, process, and parse CSV from text files using Python.


1 Answers

Lets say you have the data in t.csv. You can hold the data in a results list, then use split on each line in the file and append the results of your split to results. Using the csv module would have done this for you, but you can replicate the delimiter behaviour with split.

with open('t.csv', 'r') as f:
    results = []
    for line in f:
            words = line.split(',')
            results.append((words[0], words[1:]))
    print results
like image 53
kaushik94 Avatar answered Oct 21 '22 04:10

kaushik94