How to import data from a CSV file and store it in a variable?


I am extremely new to python 3 and I am learning as I go here. I figured someone could help me with a basic question: how to store text from a CSV file as a variable to be used later in the code. So the idea here would be to import a CSV file into the python interpreter:

import csv
with open('some.csv', 'rb') as f:
    reader = csv.reader(f)
    for row in reader:

and then extract the text from that file and store it as a variable (i.e. w = ["csv file text"]) to then be used later in the code to create permutations:

print (list(itertools.permutations(["w"], 2)))

If someone could please help and explain the process, it would be very much appreciated as I am really trying to learn. Please let me know if any more explanation is needed!

itertools.permutations() wants an iterable (e.g. a list) and a length as its arguments, so your data structure needs to reflect that, but you also need to define what you are trying to achieve here. For example, if you wanted to read a CSV file and produce permutations on every individual CSV field you could try this:

import csv
with open('some.csv', newline='') as f:
    reader = csv.reader(f)
    w = []
    for row in reader:

print(list(itertools.permutations(w, 2)))

The key thing here is to create a flat list that can be passed to itertools.permutations() - this is done by intialising w to an empty list, and then extending its elements with the elements/fields from each row of the CSV file.

Note: As pointed out by @martineau, for the reasons explained here, the file should be opened with newline='' when used with the Python 3 csv module.