1

I'm currently have 3 different csv file with some data. I would like to insert the data into 3 different array. This is the coding i'm currently working on

arrayList = []
for index, url in enumerate(urls):
with open('filename{}.csv'.format(index),'r') as f:
    for line in f:
        while line != '':
            arrayList[index].append(line)

i know that the code will definitely not work. Is there a way that i can do it?

ali
  • 859
  • 4
  • 12
  • 25
  • 2
    There are some great libraries that make CSV reading easier. Do you want to do this by hand? Any chance this question could help you? https://stackoverflow.com/questions/3518778/how-to-read-csv-into-record-array-in-numpy – Peter Barrett Bryan Jan 20 '18 at 17:41
  • 2
    `while line != '':` doesn't make much sense, I think `if line:` is better. Also, you're trying to index your original list as though it was nested; it's not. You defined it as 1D – roganjosh Jan 20 '18 at 17:43
  • yea i realized that, managed to solve using the csv module, thanks btw! @roganjosh – ali Jan 20 '18 at 19:04

1 Answers1

1

Try this. It produces a list with three lists in it. BTW, in Python there are no "arrayLists" like in Java. There is just a "list", which behaves similar to a Java ArrayList.

arrayList = []
for index, url in enumerate(urls):
    with open('filename{}.csv'.format(index),'r') as f:
        temparr=[]
        for line in f:
            if line != '':
                temparr.append(line)
        arrayList.append(temparr)

With the CSV module:

import csv
arrayList = []
for index, url in enumerate(urls):
    with open('filename{}.csv'.format(index), 'rb') as f:
        reader = csv.reader(f)
        arrayList.append([row for row in reader])
whackamadoodle3000
  • 6,684
  • 4
  • 27
  • 44
  • I'd really recommend the csv module for this, you're just appending text that might represent a row with multiple columns. You wouldn't even need to create the inner list because the csv module would do it for you. – roganjosh Jan 20 '18 at 17:48
  • I just modified @Ezhars's code, but I agree that the CSV module would be better. Maybe I'll post another answer – whackamadoodle3000 Jan 20 '18 at 17:50
  • wow thanks, both of it works just like what i want @ᴡʜᴀᴄᴋᴀᴍᴀᴅᴏᴏᴅʟᴇ3000 – ali Jan 20 '18 at 19:02