Open main menu

CDOT Wiki β

Changes

OPS435 Python Lab 5

9 bytes added, 17:16, 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
</sourceesource><br>Let's take time a moment to review revisit the '''file read operation''' sequence. 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
13,420
edits