week 10 File Reading and Plotting Flashcards
open function
sets up file as file object, retrieves input from file
how to open a file
file = open(‘data.txt’)
z = file.readlines()
helper functions
created to help set up program (ex: read file)
steps of plotting, step 1
import matlab library
import matplotlib.pyplot as plt
steps of plotting, step 2
pass value into plot function and show
plt.plot(food)
plt.show()
steps of plotting, step 3
saving plot
plt.savefig(‘plot.png’)
shorthand notation
short ways to customize plot color and marker
customizing ticks
changing the ticks on the plot
plt.xticks(ticks, regions, rotation = ‘20’)
ticks = location you want labeled
regions = new label
rotation = tilt label
plt.legend()
makes legend of lines on graph
file.close()
closes file, after called no more reads/writes allowed to file
file.read()
returns file as a string, you can specify max bytes in ()
file.readlines()
returns file lines as elements of a list
EOF
end of file
file.write()
writes string argument to file
mode
indicates how the file is opened and permissions
‘r’
open for reading
‘w’
open for writing, creates file if one doesn’t exist
‘a’
open for appending, creates file if one doesn’t exist
’ +’
can be added to letters to specify, update mode (add reading and writing)
output buffer
output is buffered by the interpreter before being written on hard drive
how to buffer output
f = open(‘myfile.txt’, ‘w’, buffering = 100)
f.flush()
clears internal buffer of a file
what type should integers be when being written to files?
integers should be converted to strings before being written or appended to files
os module
provides access to operating system
portability
ability to access an item easily, from multiple locations
how do you reduce portability?
by hardcoding file paths as string literals
path separator
’\’, ‘/’ separator between character directories
os.path.sep
stores path separator for the current operating system
os.path.join(“sub”, “output.txt”)… output?
sub\output.txt <– windows
sub/output.txt <– mac
os.walk()
walks a directory tree, iterable object in for loop
binary data
data stored as sequence of bytes