简体   繁体   English

需要基于csv文件python中的列数创建多个变量

[英]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: 这是我的csv文件由6列组成的示例:

0.0028,0.008,0.0014,0.008,0.0014,0.008, 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; 我想创建6个变量,以便以后在程序中使用这些数字作为值; however, the number of columns WILL vary depending on exactly which csv file I open. 但是,列数将根据我打开的确切的csv文件而有所不同。

If I were to do this manually and the number of columns was always 6, I would just create the variables like this: 如果要手动执行此操作,并且列数始终为6,则只需创建如下变量:

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? 有没有一种方法可以使用for循环创建这些变量,从而不必知道列数? 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. 从您的问题来看,我知道您的csv文件只有一行,且以逗号分隔。 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. 如果是这样,并且如果您对dictionares不满意(如@Mike C.答案),则可以使用globals()将变量添加到全局命名空间,这是一个决定。

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. 现在,您可以使用任意数量的称为thickness_i的新变量,其中i是从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. 请确保所有值都在csv文件的第一行中,因为此代码将忽略第一行以外的任何行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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