This time I will bring you pythonHow to get the specified data of csv text, what are the precautions for getting the specified data of csv text in python, the following is a practical case, let’s take a look .
csv is the abbreviation of Comma-Separated Values, which is table data stored in the form of a text file, such as the following table:
can be stored as a csv file. The file content is:
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 "A.csv", how to use Python like operating Excel Extract one of the columns, that is, a field, using the csv module that comes with Python. There are two ways to do it:
First One methoduses the reader function to receive an iterable object (such as a csv file) and can return a generator from which the content of the csv can be parsed: such as the following code The entire content of the csv can be read, with rows units:
import csv with open('A.csv','rb') as csvfile: reader = csv.reader(csvfile) rows= [row for row in reader] print rows
Obtained:
[['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('A.csv','rb') as csvfile: reader = csv.reader(csvfile) column = [row[2] for row in reader] print column
Result:
['Age', '12', '13', '14', '15']
Note that all data read from csv are of str type. This method requires knowing the column number in advance, for example, Age is in column 2, and you cannot query based on the title 'Age'. The second method can be used at this time:
The second method is to use DictReader and the reader function Similarly, receiving an iterable object can return a generator, but each returned cell is placed in the value of a dictionary, and the key of this dictionary is the title (i.e. column header) of the cell. Use the following code to see the structure of DictReader:
import csv with open('A.csv','rb') as csvfile: reader = csv.DictReader(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'}]
import csv with open('A.csv','rb') as csvfile: reader = csv.DictReader(csvfile) column = [row['Age'] for row in reader] print column
will get:
['12', '13', '14', '15']
How does python batch read txt files into DataFrame format
How does Python call mysql to update data?
The above is the detailed content of Python obtains the specified data method of csv text. For more information, please follow other related articles on the PHP Chinese website!