使用python直接读取CSV文件列到变量名称 [英] reading a CSV files columns directly into variables names with python

查看:918
本文介绍了使用python直接读取CSV文件列到变量名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要将CSV文件的列直接读入变量。结果应该是类似于你将得到与下面的shell行:
while IFS =,读ColumnName1 ColumnName2 ColumnName3
do stuff

I want to read a CSV file's columns directly into variables. The result should be something like you would get with the following shell line: while IFS=, read ColumnName1 ColumnName2 ColumnName3 do stuff

到目前为止答案似乎是与csv.DictReader,但我还没有能够使它的工作。我没有标题行,所以必须手动创建列名称。 (使用字典我认为形式mydictionary = {'ColumnName1':0,'ColumnName2':1,'ColumnName3':3})

So far the answer seems to be with csv.DictReader, but I have not been able to make it work. I do not have a header row, so column names would have to be created manually. (with a dictionary I think in the form mydictionary={ 'ColumnName1':0, 'ColumnName2':1, 'ColumnName3':3 } )

列被引用为简单变量名称,或者必须使用list [index]样式引用。代码示例只是打印列的名称是不错的。感谢您的帮助。

Also, can the columns be referenced as simple variable names or must you use a list[index] style reference. A code sample just printing the columns by name would be nice. Thanks for the help.

推荐答案

内置的 CSV 模块在使用csv文件时非常有用。

The built-in CSV Module is quite useful when working with csv files.

如果你正在查看DictReader,那么你必须使用它。

Oh, nevermind, you must be using it already, if you are looking at DictReader.

没有头将是读取第一行,解析它的逗号(因此的列数),然后设置我的字典/列表包含来自csv文件的值(使用列数,并给出每个列我的代码中的一个名称。)我可以提供一个例子,如果有必要,很简单。

The usual way I deal with files that have no header would be to read the first line, parse it for the number of commas (and hence the number of columns) then set up my dictionary/list to contain the values from the csv file (using number of columns and giving each column a name in my my code.) I can provide an example if necessary, it's pretty straightforward.

更好地了解你的问题,这是你正在寻找什么?:

I think I better understand your question, is this more what you are looking for?:

mydictionary={ 'ColumnName1':[dataRow1Col1, dataRow2Col1, dataRow3Col1], 
               'ColumnName2':[dataRow1Col2, dataRow2Col2, dataRow3Col2], 
               'ColumnName3':[dataRow1Col3, dataRow2Col3, dataRow3Col3] }

在这种情况下,这样的东西可能工作:

In which case, something like this may work:

import csv
Col1 = "ColumnName1"
Col2 = "ColumnName2"
Col3 = "ColumnName3"
mydictionary={Col1:[], Col2:[], Col3:[]}
csvFile = csv.reader(open("myfile.csv", "rb"))
for row in csvFile:
  mydictionary[Col1].append(row[0])
  mydictionary[Col2].append(row[1])
  mydictionary[Col3].append(row[2])

这篇关于使用python直接读取CSV文件列到变量名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆