Lab 8:1/0, Files, and APIs Objectives: • Explain how to read and write to files using the file. • Explain how to make us
-
- Site Admin
- Posts: 899603
- Joined: Mon Aug 02, 2021 8:13 am
Lab 8:1/0, Files, and APIs Objectives: • Explain how to read and write to files using the file. • Explain how to make us
Reading from a file: is used to read information or content from a text file. There are three ways to read data from a text file: read(): Returns the read bytes in form of a string. Reads n bytes, if non specified, reads the entire file. readline(): Reads a line of the file and returns in form of a string. For specified n, reads at most n bytes. However, does not reads more than one line, even if n exceeds the length of the line readlines(): Reads all the lines and return them as each line a string element in a list. Closing a file: close() function closes the file and frees the memory space acquired by that file. It is used at the time when the file is no longer needed or if it is to be opened in a different file mode. What is an API? An application programming interface (API) is a protocol intended to be used as an interface by software components to communicate with each other. • Numpy is a general-purpose array-processing package. It provides a high-performance multidimensional array object, and tools for working with these arrays. It is the fundamental package for scientific computing with Python. We need to import numpy class: import numpy as np • Matplotlib is the most used Python package for 2D-graphics. It provides both a quick way to visualize data from Python and publication-quality figures in many formats. We need to import matplotlib.pyplot class: import matplotlib.pyplot as plt Lab Exercise: Write a Python program to open a text file "data.txt" for reading and writing mode ('w+'). Write in it a string of n integer random numbers (as students' grade), where n will be entered by the user. Then read the data from the same file by using loadtxt method in Numpy and save it in an array of integers named y_array. Create an array of integer numbers in the range from 1 to n named x_array. Display a bar chart of x_array and y_array as shown in the sample output. a
Sample output: How many grades you want to create? 15 CpE 201 Course 80 Grades 70 60 50 40 Grade 5 8 8 30 Ib. 20 10 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Student no. "data.txt" file content: 81 21 64 58 22 46 23 28 38 20 71 36 8 11 17