Changes

Jump to: navigation, search

OPS435 Python Lab 5

105 bytes added, 16:31, 4 September 2017
PART 1 - Reading Data From Files
Third line
Last line
</source><br>In order to read data from a text file, we need to create a special storage area (or a '''"buffer"''') that will be used to access and storage the data in a file. This special storage has different names for various programming languages (like a '''"file pointer"''' in the C programming language or as an '''"object"''' in object oriented programming languages).<br><br>In Python, we define an '''object''' to store act as a buffer to help access the retrieved datacontained within the file. To simplify things for now, you can think of an '''object''' as a '''special variable'''. You will learn more about object oriented programming later in this lab.<br><br>
:#Now lets write some python code from the ipython3 prompt to open this created file for reading. We will define and object called '''"f"''' in order to act as a buffer to store the retrieved content from our text file. Issue the following:<source lang="python">
f = open('data.txt', 'r')
</source><br>The '''open()''' function takes two string arguments: a path to a file, and a mode option for reading, writing, appending, etc. The ''open()'' function will return a special object to us, this object will allow us to read the lines inside the file.<br><br>As mentioned above, objects are considered special variables that can contain attributes and methods. We can obtain these attributes and methods by using :#You may recall that we used the dir() functionto display library information for our Python library (eg. Does this seem familiar? It should since we used the dir(sys) function in a previous lab, which showed us ). We can do the attributes and methods same for another our defined objectcalled "f".<br><br>:#Issue the following:<source lang="python">
dir(f)
</source>
:#Although the '''dir(f)''' function displays a lot of information, we will focus on only a few elements. Lets inspect some of the '''functions'''. '''attributes ''' and '''methods ''' that we can use on this file object.<source lang="python">
help(f.read) # help for reading all lines and stores in a string
help(f.readlines) # help for reading all lines and stores in a list
13,420
edits

Navigation menu