Open main menu

CDOT Wiki β

Changes

OPS435 Python Lab 5

9 bytes removed, 16:44, 4 September 2017
PART 1 - Reading Data From Files
:#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 help retrieve 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.:#You may recall that we used the '''dir() ''' function to display library information for our Python library (eg. '''dir(sys) ''' ). We This function can do the same also display other elements such as attributes and methods for our defined an object called "f". 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 Separately issue the following commands in order to inspect some of the '''functions'''. '''attributes''' and '''methods''' that we can use on with 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
help(f.readline) # help for reading first line, if run a second time it will read the second line, then third
help(f.writable) # help for writing all lines and stores in determining if a stringfile is writable
help(f.close) # help for closing the opened file
f.writable() # Object method (function returns value)
13,420
edits