简体   繁体   English

Python:读取csv文件并将列保存为变量

[英]Python: reading in a csv file and saving columns as variables

I'm wanting to read in a csv and save the first two columns as variables. 我想读取一个csv并将前两列保存为变量。 This is what I have so far: 这是我到目前为止:

import sys, os, subprocess, shutil, time, string #these are for other things in the program :)
import csv

csvfile = list(csv.reader(open('test.csv')))   #read in the csv file

csv_dic = []

for row in csvfile:
        csv_dic.append(row);

for row in csv_dic:
       for column in row:
             print column, "***",   #I can print out the column
       print

I can print out columns, but would like to have it so I can have different variables for column 'arrays'. 我可以打印出列,但是想拥有它,所以我可以为列'数组'提供不同的变量。

For example, I am wanting to store the first column as 'frames' and the second as 'peaks', so to have it so, for example, frames[2] holds the second value in the first column and I can reference it. 例如,我希望将第一列存储为“帧”,将第二列存储为“峰值”,以便将其存储起来,例如,frames [2]在第一列中保存第二个值 ,我可以引用它。

Thank you. 谢谢。

Here's one way to do it: 这是一种方法:

frames = []
peaks = []

for row in csv_dic:
    frames.append(row[0])
    peaks.append(row[1])
    for column in row:
        print column, "***",   #I can print out the column
    print

Note that I am making one big assumption: that the two columns you want are exactly the first two columns of the CSV file. 请注意,我做了一个很大的假设:您想要的两列正好是CSV文件的前两列。 But this should do what you want. 但这应该做你想要的。 row[0] is the value in the first column of the row, and likewise, row[1] is the second column. row[0]row[0]的第一列中的值,同样, row[1]是第二列。

Now, if you want to do an unknown number of columns, you'll have to use another method (like a dictionary, perhaps). 现在,如果你想做一个未知数量的列,你将不得不使用另一种方法(也许是字典)。

Simple to do with the CSV module which you are already using. 与您已经使用的CSV模块一起使用很简单。 Here is a dictionary method and an array method. 这是一个字典方法和一个数组方法。

dictionary 字典

import csv
var1 = "frames"
var2 = "peaks"
csv_dic={var1:[], var2:[]}
csvFile = csv.reader(open('test.csv', 'rb'))
for row in csvFile:
  csv_dic[var1].append(row[0])
  csv_dic[var2].append(row[1])

again assuming that you only are worried about first two elements of each row. 再假设你只担心每一行的前两个元素。

Here is a method that will get you everything into your array, here called data . 这是一个方法,可以将所有内容都放入数组中,这里称为data This is relatively fast for large files. 这对于大文件来说相对较快。

array 排列

import csv
with open('test.csv','rb') as file:
    rows = csv.reader(file, 
                      delimiter = ',', 
                      quotechar = '"')
    data = [data for data in rows]

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

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