13,420
edits
Changes
→PART 1 - Reading Data From Files
f.close() # This method will close the file
f.closed # Confirm that the file is closed
</source>:#All together <br>Let's review. The following code sequence will open a file, store the code for reading from contents of a file into a variable, close the file should look like and provide confirmation that the followingfile has been closed:<source lang="python"pre>f = open('data.txt', 'r') # Open file
read_data = f.read() # Read from file
f.close() # Close file
f.closed # Confirm file is closed
</sourcepre>
:#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