程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python operates csv Dictreader() method

編輯:Python

Catalog

Easy to use csv.DictReader() Method

Use csv.DictReader() And fieldnames Parameters

Use csv.DictReader() And restkey Parameters

Use csv.DictReader() And restval Parameters

Easy to use csv.DictReader() Method

Sample code 1:

import csvf = open('sample','r',encoding='utf8')reader = csv.DictReader(f)print(reader) # <csv.DictReader object at 0x000002241D730FD0>for line in reader: # reader For ease of understanding, we can think of it as a nested list OrderedDict( A data type that looks like a list )    print(line) # OrderedDict([('id', '1'), ('name', 'jason'), ('age', '18')]) 

sample For one txt file , The contents of the document are as follows :

id,name,age1,jason,182,jian,203,xiaoming,304,dog,40

The result of the code running on the terminal is :

<csv.DictReader object at 0x000001FCF6FA0FD0>    # From the sample code 1 Medium print(reader)
OrderedDict([('id', '1'), ('name', 'jason'), ('age', '18')])    # From the sample code 1 Medium print(line)
1 jason 18    # From the sample code 1 Medium print(line['id'],line['name'],line['age'])
OrderedDict([('id', '2'), ('name', 'jian'), ('age', '20')])
2 jian 20
OrderedDict([('id', '3'), ('name', 'xiaoming'), ('age', '30')])
3 xiaoming 30
OrderedDict([('id', '4'), ('name', 'dog'), ('age', '40')])
4 dog 40

OrderedDict Is a data type that looks like a list , The list is nested with tuple instances :line = OrderedDict([('id', '1'), ('name', 'jason'), ('age', '18')]), The first element in each tuple is the key , The second element is the value ( It's like a dictionary ), Where do the keys in each tuple come from ?== By default ( You can set it yourself )==csv.DictReader() The first line of data read is the key . And it can be retrieved by index OrderedDict The value in the data print(line['id'],line['name'],line['age']) # Index values can be obtained through the key ( It's like a dictionary ).

Use csv.DictReader() And fieldnames Parameters

stay reader = csv.DictReader(f,fieldnames=['new_id','new_name','new_age']) Add parameters in fieldnames=['new_id','new_name','new_age'] Used to specify keys .

Sample code 2:

import csvf = open('sample','r',encoding='utf8')# adopt fieldnames Parameter specifies the field reader = csv.DictReader(f,fieldnames=['new_id','new_name','new_age'])head_row = next(reader) # next() Method to move the pointer print(reader) # <csv.DictReader object at 0x000002241D730FD0>for line in reader: # reader For ease of understanding, we can think of it as a nested list OrderedDict( A data type that looks like a list )    print(line) # OrderedDict([('new_id', '2'), ('new_name', 'jian'), ('new_age', '20')])     # Index values through the specified fields and print out     print(line['new_id'],line['new_name'],line['new_age']) # Index values can be obtained through the key ( It's like a dictionary )

next() Method to move the pointer , Sample code 2 Medium head_row = next(reader) Get the first row of data stored in head_row in , Do it once next() The pointer moves one line , The pointer has moved to the beginning of the second line , When reading data again , Just start reading from the second line . If not implemented head_row = next(reader) Then there will be more such results in the output OrderedDict([('new_id', 'id'), ('new_name', 'name'), ('new_age', 'age')]) The first row of data is also included .

The result of the code running on the terminal is :

<csv.DictReader object at 0x000001D329CF2080>    # From the sample code 2 Of print(reader) 
OrderedDict([('new_id', '1'), ('new_name', 'jason'), ('new_age', '18')])    # From the sample code 2 Of print(line)
1 jason 18    # From the sample code 2 Of print(line['new_id'],line['new_name'],line['new_age'])
OrderedDict([('new_id', '2'), ('new_name', 'jian'), ('new_age', '20')])
2 jian 20
OrderedDict([('new_id', '3'), ('new_name', 'xiaoming'), ('new_age', '30')])
3 xiaoming 30
OrderedDict([('new_id', '4'), ('new_name', 'dog'), ('new_age', '40')])
4 dog 40

Use csv.DictReader() And restkey Parameters

If the read row has more values than the key name sequence , At this point, the remaining data will be added as values to restkey Under the key in . At this point we modify sample Add one more column of data to the file .
stay reader = csv.DictReader(f,fieldnames=['new_id','new_name','new_age'],restkey='hobby') Add restkey='hobby' Used to specify the key to receive extra values , And pay attention to restkey Only one value can be passed in , Cannot pass in list , Tuple data type .

sample For one txt file , The contents of the document are as follows :

id,name,age1,jason,18,dbj2,jian,20,lol3,xiaoming,30,game4,dog,40,noting

Sample code 3:

import csvf = open('sample','r',encoding='utf8')# adopt fieldnames Parameter specifies the field , beyond fieldnames The value of the number of middle keys , use restkey To receive reader = csv.DictReader(f,fieldnames=['new_id','new_name','new_age'],restkey='hobby')head_row = next(reader) # next Used to move the pointer print(reader) # <csv.DictReader object at 0x000002241D730FD0>for line in reader: # reader For ease of understanding, we can think of it as a nested list OrderedDict( A data type that looks like a list )    print(line) # OrderedDict([('new_id', '2'), ('new_name', 'jian'), ('new_age', '20')])     # Index values through the specified fields and print out     print(line['new_id'],line['new_name'],line['new_age'],line['hobby']) # Index values can be obtained through the key ( It's like a dictionary )

The result of the code running on the terminal is :

<csv.DictReader object at 0x000001CB6B6030F0>    # From the sample code 3 Of print(reader) 
OrderedDict([('new_id', '1'), ('new_name', 'jason'), ('new_age', '18'), ('hobby', ['dbj'])]) # From the sample code 3 Of print(line)
1 jason 18    # From the sample code 3 Of print(line['new_id'],line['new_name'],line['new_age'])
OrderedDict([('new_id', '2'), ('new_name', 'jian'), ('new_age', '20'), ('hobby', ['lol'])])
2 jian 20
OrderedDict([('new_id', '3'), ('new_name', 'xiaoming'), ('new_age', '30'), ('hobby', ['game'])])
3 xiaoming 30
OrderedDict([('new_id', '4'), ('new_name', 'dog'), ('new_age', '40'), ('hobby', ['noting'])])
4 dog 40

From the results of the code run, we will find the extra values , Do use restkey Specified key restkey='hobby' Here we go OrderedDict([('new_id', '1'), ('new_name', 'jason'), ('new_age', '18'), ('hobby', ['dbj'])])
Note that although extra keys can be used restkey The specified key receives , But it can't be printed by index , Which is execution print(line["hobby"]) That would be wrong KeyError: 'hobby'.

Use csv.DictReader() And restval Parameters

If the read row has fewer values than the key name sequence , At this point, the remaining keys will use optional parameters restval The value in . At this point we modify sample Add one more column of data to the file .
stay reader = csv.DictReader(f,fieldnames=['new_id','new_name','new_age','hobby'],restval='others') Add restval='others' Used to specify the default value when the key corresponding value is null , And pay attention to restval Only one value can be passed in , Cannot pass in list , Tuple data type .

sample For one txt file , The contents of the document are as follows :

id,name,age1,jason,182,jian,20,lol3,xiaoming,304,dog,40,noting

Sample code 4:

import csvf = open('sample','r',encoding='utf8')# adopt fieldnames Parameter specifies the field , beyond fieldnames The value of the number of middle keys , use restkey To receive reader = csv.DictReader(f,fieldnames=['new_id','new_name','new_age','hobby'],restval='others')head_row = next(reader) # next Used to move the pointer # print(reader) # <csv.DictReader object at 0x000002241D730FD0>for line in reader: # reader For ease of understanding, we can think of it as a nested list OrderedDict( A data type that looks like a list )    print(line) # OrderedDict([('new_id', '1'), ('new_name', 'jason'), ('new_age', '18'), ('hobby', 'others')])     # Index values through the specified fields and print out     print(line['new_id'],line['new_name'],line['new_age'],line['hobby']) # Index values can be obtained through the key ( It's like a dictionary )

The result of the code running on the terminal is :

OrderedDict([('new_id', '1'), ('new_name', 'jason'), ('new_age', '18'), ('hobby', 'others')])  # From the sample code 4 Of print(line)
1 jason 18 others  # From the sample code 4 Of print(line['new_id'],line['new_name'],line['new_age'],line['hobby'])
OrderedDict([('new_id', '2'), ('new_name', 'jian'), ('new_age', '20'), ('hobby', 'lol')])
2 jian 20 lol
OrderedDict([('new_id', '3'), ('new_name', 'xiaoming'), ('new_age', '30'), ('hobby', 'others')])3 xiaoming 30 others
OrderedDict([('new_id', '4'), ('new_name', 'dog'), ('new_age', '40'), ('hobby', 'noting')])
4 dog 40 noting

This is about python operation csv Format file csv.DictReader() This is the end of the article on Methods , More about python csv.DictReader Please search the previous articles of SDN or continue to browse the related articles below. I hope you will support SDN more in the future !



  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved