1,234
edits
Changes
no edit summary
f.closed # Object attribute (confirm if file is closed)
</source>
:#Next, issue the following commands to read data from the buffer of the opened file and store the contents into a variable called "<code>read_data"</code>, and then confirm the contents of the variable "<code>read_data</code>:<source lang="python">
read_data = f.read()
read_data
f = open('data.txt', 'r') # Open file
read_data = f.read() # Read from file
f.close() # Close file</source><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 filef.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>:#Let's re-issue look at the following commandcontents of:<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 the special character ''''\n'''' which represents the '''newline character''' in a file used to separate lines (or records in a traditional "flat database file"). It would be convenient to '''split''' the line on the new-line characters, so each line can be stored into a separate array elements (or in our case, a list!).<br><br>