O'Reilly logo

Sage Beginner's Guide by Craig Finch

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Time for action - reading data from a text file

Now, we will read the data from the text file. This is a good place to demonstrate the while loop, since we won't always know in advance how many lines are in the file. Run the following code to load the data.

 from matplotlib import pyplot as plt import os path = '/Users/cfinch/Documents/Writing/Sage for Beginners/Chapters/Chapter 4/' fileName = 'data.txt' # Read in the data file times = [] data = [] text_file = open(os.path.join(path, fileName), 'r') line = text_file.readline() while len(line) > 0: print(line) # split each line into a list of strings elements = line.split(',') # Strip newlines and convert strings to real numbers times.append(float(elements[0].strip())) data.append(float(elements[1].strip())) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required