Changes

Jump to: navigation, search

OPS435 Python Lab 5

33 bytes added, 17:03, 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
</source><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>
:#Another way to read data from a file is using the with statement. The advantage here is that it will automatically close() the file when complete:<source lang="python">
with open('data.txt', 'r') as f: # Open file
13,420
edits

Navigation menu