-3

So I have to split my data from a csv file.(Haven't worked with python a lot.)

The code I'm using is:

data = open('C:\DATA\data.csv','r')
rdata=[]
lines_data=data.readlines()
col_number = 30
for s in range(col_number):
    for x in lines_data:
        rdata.append(x.split(',')[s])
data.close()
print(rdata)

The result I'm getting is one single list that contains all numbers, but I wanna get 31. What should I do? *I am not supposed to use any libraries

edit the data set I'm using can be found here [https://archive.ics.uci.edu/ml/datasets/Breast+Cancer+Wisconsin+(Diagnostic)]

the output data is something like this :

['17.99', '20.57', '19.69', '11.42',........'0.124', '0.07039']

which is a list with many numbers but as I mentioned before I want to get a list that contains 31 columns.Thank you in advance :)

Ma Ov
  • 1
  • 2

2 Answers2

-1

First of all, rolling your own CSV reader is generally a bad idea – it is surprisingly hard to get it right! Use the csv module from the standard library. However, since you seem to be in a classroom situation, maybe you have to.

The reason that you are getting all numbers in a single list is that you are creating a single list and appending each number to it!

I looks like you want 31 lists, one for each column. The obvious way to do this would be to create a list of 31 empty lists, then iterate over the input file and, for each row, iterate over the columns and append the value from the column to the corresponding list.

Ture Pålsson
  • 6,088
  • 2
  • 12
  • 15
-2

In actual python, you'd read a simple csv file like this:

with open(r'C:\DATA\data.csv') as fp:
    rdata = [line.split(',') for line in fp]
gog
  • 10,367
  • 2
  • 24
  • 38
  • 6
    what if there are commas, inside a field, properly quoted? You are just guessing without knowing the input file – buran Oct 04 '22 at 11:49
  • @buran: ^^^ a _simple_ csv file. For "what if" cases, `import csv` – gog Oct 04 '22 at 11:51
  • 1
    That's why I marked as dupe and clear XY problem. You should have done the same. _simple csv file_ does not exclude quoted sep in the field – buran Oct 04 '22 at 11:51