简体   繁体   中英

Need to create multiple variables based on number of columns in csv file python

This is and example of what my csv file looks like with 6 columns:

0.0028,0.008,0.0014,0.008,0.0014,0.008,

I want to create 6 variables to use later in my program using these numbers as the values; however, the number of columns WILL vary depending on exactly which csv file I open.

If I were to do this manually and the number of columns was always 6, I would just create the variables like this:

thickness_0 = (row[0])
thickness_1 = (row[1])
thickness_2 = (row[2])
thickness_3 = (row[3])
thickness_4 = (row[4])
thickness_5 = (row[5])

Is there a way to create these variables with a for loop so that it is not necessary to know the number of columns? Meaning it will create the same number of variables as there are columns?

There are ways to do what you want, but this is considered very bad practice, you better never mix your source code with data.

If your code depends on dynamic data from "outer world", use dictionary (or list in your case) to access your data programatically.

You can use a dictionary

mydict = {}

    with open('StackupThick.csv', 'r') as infile:
        reader = csv.reader(infile, delimiter=',')
        for idx, row in enumerate(reader):
            key = "thickness_" + str(idx)
            mydict[key] = row

Call your values like this:

print(mydict['thickness_3'])

From your question, I understand that your csv files have only one line with the comma separated values. If so, and if you are not fine with dictionares (as in @Mike C. answers) you can use globals() to add variables to the global namespace, which is a dict.

import csv

with open("yourfile.csv", "r", newline='') as yourfile:
    rd = csv.reader(yourfile, delimiter=',')
    row = next(rd)
    for i, j in enumerate(row):
        globals()['thickness_' + str(i)] = float(j)

Now you have whatever number of new variables called thickness_i where i is a number starting from 0.

Please be sure that all the values are in the first line of the csv file, as this code will ignore any lines beyond the first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM