\
or /
file = open('<file_name>')
file.close()
try, finally
reader = open('dog_breeds.txt')
try:
# Further file processing goes here
finally:
reader.close()
with
with open('dog_breeds.txt', 'r') as reader:
# Further file processing goes here
open()
'r'
= open for reading (default)'w'
= open for writing, truncating (overwriting) the file first'rb'
or 'wb'
= open in binary mode (read/write using byte data).read(size=-1)
None
or -1
is passed, then the entire file is read..readline(size=-1)
size
number of characters from the line. This continues to the end of the line and then wraps back around. If no argument is passed or None
or -1
is passed, then the entire line (or rest of the line) is read.readlines()
write(string)
writelines(seq)
__file__
os.getcwd()
to get the current working directory of your executing code.'a'
character
Append to a file or start writing at the end of an already populated file
with open('dog_breeds.txt', 'a') as a_writer:
a_writer.write('\nBeagle')
Can create custom exceptions using raise
x = 10
if x > 5:
raise Exception('x should not exceed 5. The value of x was: {}'.format(x))
#Returns
Traceback (most recent call last):
File "<input>", line 4, in <module>
Exception: x should not exceed 5. The value of x was: 10
false
assert
that a condition exists, and if True
the program will executeimport sys
assert ('linux' in sys.platform), "This code runs on Linux only."
#Returns
Traceback (most recent call last):
File "<input>", line 2, in <module>
AssertionError: This code runs on Linux only.
try, except, else, finally
try
says, “run this block of code if there are no exceptions”except
says, “run this block of code if there is an exception”else
says, “run this block of code next if there are no exceptions”finally
says, “after all of the above, then do this code”