One of the most common tasks that you can do with Python is reading and writing files.
open()
built-in function.try-finally
block:reader = open('dog_breeds.txt')
try:
# Further file processing goes here
finally:
reader.close()
with
statement. The with statement automatically takes care of closing the file once it leaves the with block, even in cases of error:with open('dog_breeds.txt') as reader:
# Further file processing goes here
r
- Open for reading (default)w
- Open for writing, truncating (overwriting) the file firstrb
or wb
- Open in binary mode (read/write using byte data).read(size=-1)
- This reads from the file based on the number of size bytes. If no argument is passed or None or -1 is passed, then the entire file is read..readline(size=-1)
- This reads at most 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()
- This reads the remaining lines from the file object and returns them as a list.>>> with open('dog_breeds.txt', 'r') as reader:
>>> # Read and print the entire file line by line
>>> for line in reader:
>>> print(line, end='')
.write(string)
- This writes the string to the file..writelines(seq)
- This writes the sequence to the file. No line endings are appended to each sequence item. It’s up to you to add the appropriate line ending(s)..write()
and .writelines()
:with open('dog_breeds.txt', 'r') as reader:
# Note: readlines doesn't trim the line endings
dog_breeds = reader.readlines()
with open('dog_breeds_reversed.txt', 'w') as writer:
# Alternatively you could use
# writer.writelines(reversed(dog_breeds))
# Write the dog breeds to the file in reversed order
for breed in reversed(dog_breeds):
writer.write(breed)
__file__
attribute is a special attribute of modules, similar to __name__
. It is the pathname of the file from which the module was loaded, if it was loaded from a file.Source: https://realpython.com/read-write-files-python/
In Python, an error can be a syntax error or an exception.
raise
to throw an exception if a condition occurs. The statement can be complemented with a custom exception:x = 10
if x > 5:
raise Exception('x should not exceed 5. The value of x was: {}'.format(x))
AssertionError
Exceptionassert
that a certain condition is met. If this condition turns out to be True
, then that is excellent! The program can continue. If the condition turns out to be False
, you can have the program throw an AssertionError
exception:import sys
assert ('linux' in sys.platform), "This code runs on Linux only."
try
and except
Block: Handling Exceptionstry
and except
block in Python is used to catch and handle exceptions. Python executes code following the try statement as a “normal” part of the program. The code that follows the except statement is the program’s response to any exceptions in the preceding try
clause.try:
linux_interaction()
except AssertionError as error:
print(error)
print('The linux_interaction() function was not executed')
try:
with open('file.log') as file:
read_data = file.read()
except FileNotFoundError as fnf_error:
print(fnf_error)
else
Clauseelse
statement, you can instruct a program to execute a certain block of code only in the absence of exceptions:try:
linux_interaction()
except AssertionError as error:
print(error)
else:
print('Executing the else clause.')
finally
finally
clause:try:
linux_interaction()
except AssertionError as error:
print(error)
else:
try:
with open('file.log') as file:
read_data = file.read()
except FileNotFoundError as fnf_error:
print(fnf_error)
finally:
print('Cleaning up, irrespective of any exceptions.')