Assessment 3 Flashcards
open a file
my_file = open(‘filename’, ‘access mode’)
close a file
my_file.close()
access modes for reading
r or rt
access modes for writing
wt or w
access modes for appending
at or a
reading/writing in binary format
rb or wb
return the whole file in one big string
file_handle.read()
returns a single line of the file in a string each time
file_handle.readline()
where does file_handle.readline() set the cursor to
the next line
move the cursor manually
file_handle.seek()
how to loop over a file
for line in file_handle:
print(line)
writes a single string into the file
.write()
file_handle.write(‘dfdfdf\n’)
writes a list of strings into the file ~ doesn’t add new line characters (or anything else) in between
.writelines()
using a content manager:
with open(“filename”, “access mode”) as file_handle:
when using a content manager, do I need to close it
no, once leaving the indentation from the header, the file is automatically closed by python
what does buffered mean
files aren’t updated until you close the file object in python
what do you put under the try block
you write the code that you expect may throw an error
what do you put under the except block
code to execute if an error occurs
what do I import to deal with csv files
import csv
parameters for csv.reader
csv.reader(file_object, delimiter = ‘,’)
what are the parameters for csv.DictReader
csv.DictReader(file_object,fieldnames)
if the filename parameter for csv.DictReader is not specified
the keys default to the first row
what are the parameters for csv.writer
csv.writer(file_object, delimiter = ‘,’, lineterminator = ‘\n’)
how should the filenames parameter be passed in for csv.DictReader
reader = csv.DictReader(my_file, fieldnames = [‘word’, ‘num’])
what is the data type of output with open("example.csv") as my_file: reader = csv.DictReader(my_file) output = [ line for line in reader]
list
example of using sorted to sort a list of lists by the third index
sorted(aList, key = lambda x:x[2], reverse = True)
string that groups elements together and tells python to ignore any time the delimiter appears inside
quotechar of a CSV file
default value for the quotechar is :
double quote (“)
quotechar can be a parameter in
csv.reader()
convert a listed list into a dictionary in one line
other_data = [{data[0][0]: i, data[0][1]:j} for i,j in data[1:J]]