Source: Read & Write Files in Python
FIles consist of:
Header
- metadata (e.g. name, type)Data
- contentEnd of File
- character at end\r\n
for windows
Pug\r\n
Jack Russell Terrier\r\n
\r
for unix or mac
Pug\r
\n
Jack Russell Terrier\r
\n
ASCII
Unicode
Open
file = open('dog_breeds.txt')
Close
try:
# Further file processing goes here
finally:
reader.close()
Using with will close automatically
with open('dog_breeds.txt', 'r') as reader:
# Further file processing goes here
r
read (default)w
writerb
or wb
binary mode_io.TextIOWrapper
type)BufferedReader
or BufferedWriter
)_io.FileIO
)read(size=-1)
- Number of bytes, or -1 for allreadline(size=-1)
- Number of character, or -1 for allreadlines()
- Remaining lines returned as a listreadline()
with open('dog_breeds.txt', 'r') as reader:
# Read and print the entire file line by line
line = reader.readline()
while line != '': # The EOF char is an empty string
print(line, end='')
line = reader.readline()
readlines()
with open('dog_breeds.txt', 'r') as reader:
for line in reader.readlines():
print(line, end='')
file
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)
.writelines(seq)
# 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)
with open('dog_breeds.txt', 'a') as a_writer:
a_writer.write('\nBeagle')
d_path = 'dog_breeds.txt'
d_r_path = 'dog_breeds_reversed.txt'
with open(d_path, 'r') as reader, open(d_r_path, 'w') as writer:
dog_breeds = reader.readlines()
writer.writelines(reversed(dog_breeds))
Reading and Writing CSV Files in Python Working With JSON Data in Python
Source: Python Exceptions: An Introduction
Throw an exceptions (standard or custom) if certain condition occurs:
x = 10
if x > 5:
raise Exception('x should not exceed 5. The value of x was: {}'.format(x))
Results in:
Traceback (most recent call last):
File "<input>", line 4, in <module>
Exception: x should not exceed 5. The value of x was: 10
Assert that a specfic condition is met, instead of waiting for failure:
import sys
assert ('linux' in sys.platform), "This code runs on Linux only."
Results in:
Traceback (most recent call last):
File "<input>", line 2, in <module>
AssertionError: This code runs on Linux only.
Try some code, and catch an exception if it occurs
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:
print('Could not open file.log')
Runs in absense of error:
try:
linux_interaction()
except AssertionError as error:
print(error)
else:
print('Executing the else 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)
Use finally to clean up after code execution
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.')
raise
to throw an exception at any timeassert
enables to verify certain condition istry
all statements executed until an exceptionexcept
to catch / handle exception(s) in try clauseelse
run only when no exceptions in try clausefinally
to execute code to always run regardless of exception