Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to load data from a file by Python

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces "how to load data from a file by Python". In daily operation, I believe that many people have doubts about how to load data from a file by Python. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the question of "how to load data from a file by Python". Next, please follow the editor to study!

We will load the CSV file using the built-in csv module

CSV file is a special text file. The data in the file is delimited by commas, which is very suitable for data parsing. First use excle to create the following tables and data, save as csv format file, and put it in the code directory.

Included in the Python standard library with its own CSV module, we only need import to come in to use. For example, we need to print out all the above CSV files. The code is as follows:

Import csv # import csv is used to import the absolute path saved by the csv module filename ='E:\ WorkSpace\ python\ coding\ score.csv' # file with open (filename) as file_csv: # have you forgotten how to open the file? Open the file and store the resulting file object in file_csv reader = csv.reader (file_csv) # directly call to read the file contents with csv.read () read for row in reader: # print each line of print (row) with for

The running results are as follows:

['Name',' Grade', 'Class',' Age', 'mathscore',' Englishscore']

['Lucy',' 7,'2,'14,'95,'86]

['bush',' 8,'1','15','80','75']

['lily',' 7,'3,'14,'93,'95]

['Jack',' 8,'2,'14,'87,'84]

['Mary',' 9,'1','15','85','86']

['philip',' 7,'3,'14,'90,'92]

['Liming',' 9,'2,'16,'99,'87]

Print file header and its location

Read into the file, in order to get the data, need to separate the relevant information, first see how to read out the header, that is, the first line of the file, next () returns the next line in the file.

Import csv # import csv is used to import the absolute path saved by the csv module filename ='E:\ WorkSpace\ python\ coding\ score.csv' # file with open (filename) as file_csv: # have you forgotten how to open the file? Open the file and store the resulting file object in file_csv reader = csv.reader (file_csv) # directly call read with csv.read () read the file contents header_row = next (reader) # module csv contains the function next (), and when you call it and pass the reader object to it, it will return the next line in the file. # next () is called once, so the first line of the file contains the header # for row in reader: # print each line in for loop # print (row) for index, column_header in enumerate (header_row): # call enumerate () to the list to get the index of each element and its value print (index, column_header)

The result of the run is as follows:

0 Name

1 Grade

2 Class

3 Age

4 mathscore

5 Englishscore

Extract the index, that is, the index of name is 0 and the index is 1. If you know the index, you can read any data in it. For example, if we want to print out mathscore, the index is 4, so the code is as follows:

Scores = [] defines an empty file read by list for row in reader: scores.append (int (row [4])) #, which defaults to a string and is converted to a number with int (). Print (scores)

Running result:

[95, 80, 93, 87, 85, 90, 99]

Next, make a chart to show it, and first compare the mathscore and englishscore scores in a column. The code is as follows:

Import matplotlib.pyplot as pltimport csv # import csv is used to import the absolute path saved by the csv module filename ='E:\ WorkSpace\ python\ coding\ score.csv' # file with open (filename) as file_csv: # have you forgotten how to open the file? Open the file and store the resulting file object in file_csv reader = csv.reader (file_csv) # directly call read with csv.read () read the file contents header_row = next (reader) # module csv contains the function next (), and when you call it and pass the reader object to it, it will return the next line in the file. # next () is called once, so the first line of the file contains the header mathscores = [] # defines two lists englishscores= [] for row in reader: mathscores.append (int (row [4])) # reads the data with an index of 4, defaults to a string, and converts it into a number with int (). Englishscores.append (int (row [5])) # reads data with an index of 5 and converts it into a number with int (). Plt.bar (englishscores, label='englis', color='g') plt.legend () plt.title ('scores') plt.show ()

Those print-related codes have been deleted. Look at the running results:

Next, we read the file and draw the chart according to the time in the file

Create a new year of data (really fabricated data), the first column is the year, the second column is the number of graduates each year, and the third column is the number of annual applicants, as shown in the figure:

Request:

1. The number of each year is shown by year, and expressed in different colors.

2. Other colors are also used to fill between the two.

The completion code is as follows:

Import matplotlib.pyplot as pltimport csv # import csv is used to import the csv module from datetime import datetime # introduce the time-dependent module filename ='E:\ WorkSpace\ python\ coding\ graduatesNumbers.csv' # the absolute path saved by the file with open (filename) as file_csv: # have you forgotten how to open the file? Open a file And store the result file object in file_csv reader = csv.reader (file_csv) # directly call to read the file contents with csv.read () header_row = next (reader) dates= [] numbers= [] application_numbers= [] for row in reader: current_date = datetime.strptime (row [0]) "% Y/%m/%d") # year The function dates.append (current_date) numbers.append (int (row [1])) #, which converts strptime () date format to string format, reads the data with an index of 1, defaults to a string, and converts it to a number with int (), that is, Numbers of graduates. Application_numbers.append (int (row [2])) # reads data with index 2 That is, Number of applicants plt.plot (dates,numbers,label='Numbers of graduate', cantilever transparent plt.title') # displays the first line plt.plot (dates,application_numbers,label='Number of applicant', cantilevered green') # displays the second line application_numbers broken line plt.fill_between (dates,numbers, application_numbers, facecolor='blue', alpha=0.5) # fills the color alpha transparency plt.title ("The numbers of graduate") between the two lines Fontsize=24) plt.xlabel ('Years', fontsize=16) plt.ylabel ("The numbers", fontsize=16) plt.legend () plt.show ()

The actual running results are as follows:

At this point, the study of "how to load data from a file by Python" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report