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

标签 python csv file-io

我想读取 csv 并将前两列保存为变量。 这是我到目前为止所拥有的:

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

我可以打印出列,但希望拥有它,以便我可以为列“数组”使用不同的变量。

例如,我想将第一列存储为“frames”,第二列存储为“peaks”,因此,例如,frames[2] 保存第一列中的第二个值我可以引用它。

谢谢。

最佳答案

这是一种方法:

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

请注意,我做了一个重大假设:您想要的两列正是 CSV 文件的前两列。但这应该可以达到你想要的效果。 row[0] 是该行第一列中的值,同样,row[1] 是第二列。

现在,如果您想要执行未知数量的列,则必须使用另一种方法(也许像字典)。

关于Python:读取 csv 文件并将列保存为变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33928399/

相关文章:

python - 使用python将带有俄语字符的二维数组打印到csv

python - 有没有办法将我从 .txt 文件中检索到的整数相加

php - 将数据库转换为 CSV 并将文件保存到服务器上的文件夹

python - 我收到错误 : rest_framework. request.WrappedAttributeError: 'CSRFCheck' object has no attribute 'process_request'

Python如何检查for循环中的最后一个元素?

python - Python 请求的超时值是指收到的第一个字节还是整个消息?

java - 创建多个文件目录

java.io.IOException : The system cannot find the path specified 异常

c - 使用 C 将 CFG 从文件读取到链表中

python - 自定义类对象和 "in"集合运算符