How to Create Arrays From a CSV With Python

104 109
    • 1). Launch the Python command-line interpreter.

    • 2). Type the following commands to make use of the "csv" and "array" modules:

      import csv

      from array import array

    • 3). Create an array called "data" to store the values from the CSV file:

      data = array('i')

      For this example, it is assumed that the values in the CSV file are signed integers. Consult the documentation for the "array" module at Docs.python.org if you need to specify a different data type.

    • 4). Open a CSV file for reading with the "open" command, specifying the file name as the first argument:

      file = open('csvfile.csv', newline='')

      The file path for Python is usually "C:\Python32\" if you're using Windows. CSV files may have various extensions, like "csv," "dat" or "txt." The "newline" argument helps avoid various compatibility problems involving newline characters.

    • 5). Use the "reader" function in the "csv" module to read from the CSV file:

      csvinput = csv.reader(file)

    • 6). Iterate through the lines of the CSV file by using a "for" loop with the "csvinput" variable:

      for lines in csvinput:

    • 7). Type the following command, enclosing it as shown to make it part of the "for" loop:

      data.fromlist([int(x) for x in lines])

    • 8). Press "Enter" to add a blank line and execute the "for" loop. The data from the CSV file are parsed as integers and added to the "data" array.

    • 9). Type "data" and press "Enter" to see that the array has been filled with the integers stored in the CSV file.

Source...
Subscribe to our newsletter
Sign up here to get the latest news, updates and special offers delivered directly to your inbox.
You can unsubscribe at any time

Leave A Reply

Your email address will not be published.