Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/354.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在csv文件中单独读取列名_Python - Fatal编程技术网

Python 在csv文件中单独读取列名

Python 在csv文件中单独读取列名,python,Python,我有一个包含以下列的csv文件: 身份证、姓名、年龄、性别 后面是上述列的许多值。 我试图单独阅读列名并将其放入列表中 with open('details.csv') as csvfile: rows=iter(csv.reader(csvfile)).next() header=rows[1:] re=csv.DictReader(csvfile) for row in re: print row for x in he

我有一个包含以下列的csv文件:

身份证、姓名、年龄、性别

后面是上述列的许多值。 我试图单独阅读列名并将其放入列表中

with open('details.csv') as csvfile:
   
    rows=iter(csv.reader(csvfile)).next()
    header=rows[1:]
    re=csv.DictReader(csvfile)
    for row in re:
        print row
        for x in header:
            
            print row[x]
我正在使用Dictreader,这提供了正确的详细信息:

with open('details.csv') as csvfile:
    i=["name","age","sex"]
    re=csv.DictReader(csvfile)
    for row in re:
        for x in i:
            print row[x]
但我想做的是,我需要用输入csv自动解析列列表,而不是在列表中硬编码它们

with open('details.csv') as csvfile:
   
    rows=iter(csv.reader(csvfile)).next()
    header=rows[1:]
    re=csv.DictReader(csvfile)
    for row in re:
        print row
        for x in header:
            
            print row[x]
这是一个错误

Keyerrror:'name'

在行打印行[x]中。我哪里做错了?是否可以使用Dictreader获取列名?

您可以使用函数读取标题,该函数将读取器的iterable对象的下一行作为列表返回。然后可以将文件的内容添加到列表中

import csv
with open("C:/path/to/.filecsv", "rb") as f:
    reader = csv.reader(f)
    i = reader.next()
    rest = list(reader)
现在我有了列的名称作为列表

print i
>>>['id', 'name', 'age', 'sex']
还要注意,
reader.next()
在Python3中不起作用。而是使用内置的
next()
在读取后立即获取csv的第一行,如下所示:

import csv
with open("C:/path/to/.filecsv", "rb") as f:
    reader = csv.reader(f)
    i = next(reader)

    print(i)
    >>>['id', 'name', 'age', 'sex']

感谢Daniel Jimenez提供了从我的csv中单独获取列名的完美解决方案,我扩展了他的解决方案,使用DictReader,这样我们就可以使用列名作为索引对行进行迭代。谢谢希门尼斯

with open('myfile.csv') as csvfile:

    rest = []
    with open("myfile.csv", "rb") as f:
        reader = csv.reader(f)
        i = reader.next()
        i=i[1:]
        re=csv.DictReader(csvfile)
        for row in re:
            for x in i:
                print row[x]

虽然您已经有了一个公认的答案,但我想我会为其他对不同解决方案感兴趣的人添加此选项-

  • CSV模块中Python的DictReader对象(从Python 2.6及更高版本开始)有一个名为字段名的公共属性。
可采取以下措施:

import csv

with open('C:/mypath/to/csvfile.csv', 'r') as f:
    d_reader = csv.DictReader(f)

    #get fieldnames from DictReader object and store in list
    headers = d_reader.fieldnames

    for line in d_reader:
        #print value in MyCol1 for each row
        print(line['MyCol1'])
import csv

with open('C:/mypath/to/csvfile.csv', 'r') as f:
    #you can eat the first line before creating DictReader.
    #if no "fieldnames" param is passed into
    #DictReader object upon creation, DictReader
    #will read the upper-most line as the headers
    f.readline()

    d_reader = csv.DictReader(f)
    headers = d_reader.fieldnames

    for line in d_reader:
        #print value in MyCol1 for each row
        print(line['MyCol1'])
在上面的示例中,d_reader.fieldnames返回一个标题列表(假设标题位于顶行)。 这允许

>>> print(headers)
['MyCol1', 'MyCol2', 'MyCol3']
如果您的标题在第二行(最上面一行是第1行),您可以执行以下操作:

import csv

with open('C:/mypath/to/csvfile.csv', 'r') as f:
    d_reader = csv.DictReader(f)

    #get fieldnames from DictReader object and store in list
    headers = d_reader.fieldnames

    for line in d_reader:
        #print value in MyCol1 for each row
        print(line['MyCol1'])
import csv

with open('C:/mypath/to/csvfile.csv', 'r') as f:
    #you can eat the first line before creating DictReader.
    #if no "fieldnames" param is passed into
    #DictReader object upon creation, DictReader
    #will read the upper-most line as the headers
    f.readline()

    d_reader = csv.DictReader(f)
    headers = d_reader.fieldnames

    for line in d_reader:
        #print value in MyCol1 for each row
        print(line['MyCol1'])

csv.DictReader
对象公开一个名为
fieldnames
的属性,这就是您要使用的属性。下面是示例代码,后面是输入和相应的输出:

import csv
file = "/path/to/file.csv"
with open(file, mode='r', encoding='utf-8') as f:
    reader = csv.DictReader(f, delimiter=',')
    for row in reader:
        print([col + '=' + row[col] for col in reader.fieldnames])
输入文件内容:

col0,col1,col2,col3,col4,col5,col6,col7,col8,col9
00,01,02,03,04,05,06,07,08,09
10,11,12,13,14,15,16,17,18,19
20,21,22,23,24,25,26,27,28,29
30,31,32,33,34,35,36,37,38,39
40,41,42,43,44,45,46,47,48,49
50,51,52,53,54,55,56,57,58,59
60,61,62,63,64,65,66,67,68,69
70,71,72,73,74,75,76,77,78,79
80,81,82,83,84,85,86,87,88,89
90,91,92,93,94,95,96,97,98,99
打印语句的输出:

['col0=00', 'col1=01', 'col2=02', 'col3=03', 'col4=04', 'col5=05', 'col6=06', 'col7=07', 'col8=08', 'col9=09']
['col0=10', 'col1=11', 'col2=12', 'col3=13', 'col4=14', 'col5=15', 'col6=16', 'col7=17', 'col8=18', 'col9=19']
['col0=20', 'col1=21', 'col2=22', 'col3=23', 'col4=24', 'col5=25', 'col6=26', 'col7=27', 'col8=28', 'col9=29']
['col0=30', 'col1=31', 'col2=32', 'col3=33', 'col4=34', 'col5=35', 'col6=36', 'col7=37', 'col8=38', 'col9=39']
['col0=40', 'col1=41', 'col2=42', 'col3=43', 'col4=44', 'col5=45', 'col6=46', 'col7=47', 'col8=48', 'col9=49']
['col0=50', 'col1=51', 'col2=52', 'col3=53', 'col4=54', 'col5=55', 'col6=56', 'col7=57', 'col8=58', 'col9=59']
['col0=60', 'col1=61', 'col2=62', 'col3=63', 'col4=64', 'col5=65', 'col6=66', 'col7=67', 'col8=68', 'col9=69']
['col0=70', 'col1=71', 'col2=72', 'col3=73', 'col4=74', 'col5=75', 'col6=76', 'col7=77', 'col8=78', 'col9=79']
['col0=80', 'col1=81', 'col2=82', 'col3=83', 'col4=84', 'col5=85', 'col6=86', 'col7=87', 'col8=88', 'col9=89']
['col0=90', 'col1=91', 'col2=92', 'col3=93', 'col4=94', 'col5=95', 'col6=96', 'col7=97', 'col8=98', 'col9=99']

我只是提到如何从csv文件中获取所有列名。 我正在使用熊猫图书馆

首先,我们读文件

import pandas as pd
file = pd.read_csv('details.csv')
然后,为了从输入文件中获取所有列名作为列表,请使用:-

columns = list(file.head(0))

下面是只打印csv文件的标题或列的代码

import csv
HEADERS = next(csv.reader(open('filepath.csv')))
print (HEADERS)
熊猫的另一种方法

import pandas as pd
HEADERS = list(pd.read_csv('filepath.csv').head(0))
print (HEADERS)
怎么样

with open(csv_input_path + file, 'r') as ft:
    header = ft.readline() # read only first line; returns string
    header_list = header.split(',') # returns list
我假设您的输入文件是CSV格式。
如果使用pandas,如果文件较大,则需要更多时间,因为它会将整个数据作为数据集加载。

我实际上只需要数据的第一行,这是我需要的标题,不想迭代所有数据以获取它们,所以我只做了以下操作:

import pandas as pd
data = pd.read_csv("data.csv")
cols = data.columns
with open(data, 'r', newline='') as csvfile:
t = 0
for i in csv.reader(csvfile, delimiter=',', quotechar='|'):
    if t > 0:
        break
    else:
        dbh = i
        t += 1

我认为这是
print re[x]
您会得到错误:Dictreader实例没有属性“getitem”,您可以发布文件的一些行以查看其外观吗?
id、name、age、sex 100101、Herbert、21、m 100102、Keith、18、m 100103、Jennifer、15、f
感谢您的解决方案。但我只想通过列名访问它们。假设我只需要最后3列。。。在这种情况下,我必须用索引I来做它们…例如I[0]等等。。。有可能用dictreader实现这一点吗?然后我就可以访问行[名称]。我只需要我的代码来支持多列。我关心的不仅仅是索引,还有列名。例如,如果您访问
名称
,您想检索文件中的所有名称吗?请参阅下面的更新答案。你让我开心。谢谢:)酷,对不起,我不清楚你需要什么。很高兴我能帮上忙是的我知道了。谢谢你的解决方案。您的迭代器工作得非常出色。这是一个简洁的解决方案!:)当我“升级”到python3时,
fieldnames
属性现在返回
None
。根据文件,它看起来应该还能工作,但它不能。为了它的价值。我正在使用python 3.7。我认为DictReader在python3.6中返回的内容发生了变化。有趣的是,python3.7中的hello world CSV阅读器为meThe
DictReader提供了适当的
FieldName
。fieldnames
解决方案非常有效。根据我的时间安排,比本文提到的其他方法更有效。谢谢虽然这段代码可以解决这个问题,但如何以及为什么解决这个问题将真正有助于提高您的帖子质量,并可能导致更多的投票。请记住,你是在将来回答读者的问题,而不仅仅是现在提问的人。请在回答中添加解释,并说明适用的限制和假设。