Changes

Jump to: navigation, search

OPS435 Python Lab 5

21 bytes added, 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
</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
read_data = f.read() # Read from file
f.closed # Confirm file is closed
</source><br>Let's 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 the following command:<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!).
:#First issue the following commands to get help on the '''split function''' method:<source lang="python">
dir(read_data)
help(read_data.split)
</source>
:#Next, issue the following commands to store the contents of our file into a list called '''list_of_lines''':<source lang="python">
read_data.split('\n') # Returns a list
list_of_lines = read_data.split('\n') # Saves returned list in variable
list_of_lines
</source>
:#The above works, but it's not the best way to get a list of lines. The man main benefit above is that the lines can be split in any way desired(on spaces, on periods, etc). The easiest way to just get a list of all lines can be done using the file object and it's methods.<source lang="python">
f = open('data.txt', 'r')
method1 = list(f)
13,420
edits

Navigation menu