Changes

Jump to: navigation, search

OPS435 Python Lab 5

650 bytes added, 17:15, 4 September 2017
PART 1 - Reading Data From Files
f.close() # This method will close the file
f.closed # Confirm that the file is closed
</sourcesourcee><br>Let's take time to review the file read operation. The following code sequence will open a file, store the contents of a file into a variable, close the file and provide confirmation that the file has been closed:<blockquote><br><br><span style="font-family:courier;">f = open('data.txt', 'r') # Open file<br>read_data = f.read() # Read from file<br>f.close() # Close file<br>f.closed # Confirm file is closed</span><br><br></blockquote>:#<br>Another way to read data from a file is using the '''with ''' looping statement. The advantage here by using the ''with'' loop is that it the file will automatically close() when the data within the file when completehas been completely read<br><br>:#To demonstrate, issue the following code block:<source lang="python">
with open('data.txt', 'r') as f: # Open file
read_data = f.read() # Read from file
f.closed # Confirm file is closed
</source><br>Let us take a few moments to revisit the data that has been read into the variable called '''"read_data"'''.<br><br>:#Next lets read Let's re-issue the datafollowing command:<source lang="python">
read_data
</source>:#<br>This command displays the data from the file in a single <u>long </u> string. The end of each line in the file will show a the special character ''''\n'''' which represents the '''newline character ''' in a file used to separate lines (or records in a traditional "flat database file"). Split It would be convenient to '''split''' the line on the new-line characters, so more inspection each line can be done on stored into a single line at separate array elements (or in our case, a timelist!).:#First issue the following commands to get help on the split function:<source lang="python">
dir(read_data)
help(read_data.split)
</source>
:#Next, issue the following commands to store the contents of our file into a list called list_of_lines:<source lang="python">
read_data.split('\n') # Returns a list
list_of_lines = read_data.split('\n') # Saves returned list in variable
13,420
edits

Navigation menu