How To Load Data From A .csv File Without Importing The .csv Module/library
def loadfunc(filestr): listoftuples = [] listofnumbers = [] tupleinlist = [] with open(filestr, 'r') as file: for line in file: for item in line: if item.is
Solution 1:
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.
withopen('t.csv', 'r') as f:
results = []
for line in f:
words = line.split(',')
results.append((words[0], words[1:]))
print results
Solution 2:
Considering that the input file contains input like
# in.txt# apple 23.2 24.3 25.6# banana 22.1 20.0 19.9# endfrom collections import defaultdict
defget_word_float(infile_str):
d = defaultdict(list)
withopen(infile_str) as inf:
for l in inf:
item = l.split() # split by space
d[item[0]].extend(map(float, item[1:]))
return d
print(get_word_float('in.txt'))
# defaultdict(<class 'list'>, {'apple': [23.2, 24.3, 25.6], 'banana': [22.1, 20.0, 19.9]})Solution 3:
withopen('a.csv', 'r') as f:
#read from csv line by line, rstrip helps to remove '\n' at the end of line
lines = [line.rstrip() for line in f]
results = []
for line in lines:
words = line.split(',')#get each item in one line
listOfFloat = map(float,words[1:])# convert string to float
tup = (words[0],listOfFloat)
results.append(tup)
print results
Post a Comment for "How To Load Data From A .csv File Without Importing The .csv Module/library"