Changes

Jump to: navigation, search

OPS435 Python Lab 5

10 bytes removed, 16:18, 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 a moment time to revisit review the '''file read''' sequenceoperation. 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><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 by using the ''with'' loop is that the file will automatically close when the data within the file has 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 's take a few moments to revisit the data that has been read into the variable called '''"read_data"'''.<br><br>
:#Let's re-issue the following command:<source lang="python">
read_data
13,420
edits

Navigation menu