The webmaster has written a code in Python that can extract any column of the csv, feel free to use it.Github Link
csv stands for Comma-Separated Values, which are tabular data stored in the form of a text file, such as the following table:
It can then be stored as a csv file with the contents of the file:
No.,Name,Age,Score 1,Apple,12,98 2,Ben,13,97 3,Celia,14,96 4,Dave,15,95
Assuming that the above csv file is saved as "", how to extract one of the columns, i.e., one field, using Python like operating Excel, using Python's self-containedcsv module,There are two ways to accomplish this:
The first methodUse the reader function, receive an iterable object (such as a csv file), can return a generator, you can parse out the contents of the csv from it: for example, the following code can read the entire contents of the csv, in rows:
import csv with open('','rb') as csvfile: reader = (csvfile) rows= [row for row in reader] print rows
Get:
[['No.', 'Name', 'Age', 'Score'], ['1', 'Apple', '12', '98'], ['2', 'Ben', '13', '97'], ['3', 'Celia', '14', '96'], ['4', 'Dave', '15', '95']]
To extract one of the columns, you can use the following code:
import csv with open('','rb') as csvfile: reader = (csvfile) column = [row[2] for row in reader] print column
Get:
['Age', '12', '13', '14', '15']
Note that everything read from the csv is of type str. This method requires prior knowledge of the serial numbers of the columns, e.g. Age is in column 2, and cannot be queried based on the header 'Age'.This is where the second method can be used:
The second methodIs the use of DictReader, and the reader function is similar to receive an iterable object that can return a generator, but the return of each cell is placed within the value of a dictionary, and the key of this dictionary is the title of this cell (i.e., column header). With the following code you can see the structure of the DictReader:
import csv with open('','rb') as csvfile: reader = (csvfile) column = [row for row in reader] print column
Get:
[{'Age': '12', 'No.': '1', 'Score': '98', 'Name': 'Apple'}, {'Age': '13', 'No.': '2', 'Score': '97', 'Name': 'Ben'}, {'Age': '14', 'No.': '3', 'Score': '96', 'Name': 'Celia'}, {'Age': '15', 'No.': '4', 'Score': '95', 'Name': 'Dave'}]
If we want to read a particular column of a csv with DictReader, we can query it with the column header:
import csv with open('','rb') as csvfile: reader = (csvfile) column = [row['Age'] for row in reader] print column
Just get:
['12', '13', '14', '15']
The above example of using python to get a row or column of data of a csv text is all that I have shared with you, I hope to give you a reference, and I hope that you will support me more.