Python:读取csv文件并将列保存为变量 [英] Python: reading in a csv file and saving columns as variables
问题描述
我想在csv中读取并保存前两列作为变量。
这是我到目前为止:
import sys,os,subprocess,shutil,time,string #these是在程序中的其他东西:)
import csv
csvfile = list(csv.reader(open('test.csv')))#read在csv文件
csv_dic = []
csvfile中的行:
csv_dic.append(row);
对于csv_dic中的行:
对于行中的列:
打印列,***,#I可以打印出列
print
我可以打印出列,但希望有列,因此我可以为列'数组'有不同的变量。
例如,我想将第一列存储为frames,将第二列存储为peaks,因此 frames [2]保留第一列中的第二个值,我可以参考它。
谢谢。
frames = []
peaks = []
csv_dic中的行:
frames.append(row [0])
peaks.append(row [1])$ b $ b对于行中的列:
打印列,***,#I可以打印出列
print
注意,我做一个大假设:你想要的两列是CSV文件的前两列。但这应该做你想要的。 row [0]
是该行第一列中的值,同样, row [1]
第二列。
现在,如果你想做一个未知数量的列,你必须使用另一个方法(如字典)。
I'm wanting to read in a csv and save the first two columns as variables. 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.
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. 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.
Now, if you want to do an unknown number of columns, you'll have to use another method (like a dictionary, perhaps).
这篇关于Python:读取csv文件并将列保存为变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!