import io

"""
Explanation: Disk I/O
End of explanation
"""


# The legacy way:
file = open('/tmp/some_integers_1.txt', 'w')
file.write('{}\n'.format(1))
file.write('{}\n'.format(2))
file.write('{}\n'.format(3))
file.close()

!cat /tmp/some_integers_1.txt

# The modern (pythonic) alternative:
with io.open('/tmp/some_integers_2.txt', 'w') as file:
    file.write('{}\n'.format(1))
    file.write('{}\n'.format(2))
    file.write('{}\n'.format(3))

file.closed

!cat /tmp/some_integers_2.txt

"""
Explanation: Write some integers:
End of explanation
"""


# The classic alternative:
file = io.open('/tmp/some_integers_1.txt', 'r')
while True:
    line = file.readline()
    if not line:
        break
#for i in range(3):
    print(int(line))
file.close()

# The pythonic alternarive:
with io.open('/tmp/some_integers_2.txt', 'r') as file:
    for line in file:
        print(int(line))

file.closed

"""
Explanation: Reading the file:
End of explanation
"""


import struct # See https://docs.python.org/3/library/struct.html#format-characters

with io.open('/tmp/some_integers_2.bin', 'wb') as file:
    file.write(struct.pack('h', 1)) # 2 bytes, signed int
    file.write(struct.pack('h', 2)) # 2 bytes, signed int
    file.write(struct.pack('i', 3)) # 4 bytes, signed int

with io.open('/tmp/some_integers_2.bin', 'rb') as file:
    print(struct.unpack('h', file.read(struct.calcsize('h')))[0])
    print(struct.unpack('h', file.read(struct.calcsize('h')))[0])
    print(struct.unpack('i', file.read(struct.calcsize('i')))[0])

"""
Explanation: Opening modes

r: Opens file for reading.
w: Creates file for writting. Overwrites if exists.
a: Opens file for appending (pointer at the end). Creates if does not exist.
r+: Opens file for reading and writting. Does not overwrite. Does not create.
w+: Opens file for reading and writting. Overwrites. Creates if does not exist.
a+: Opens file for appending (pointer at the end) and reading. Creates if does not exist.

Binary VS Text modes
In the previous examples we have used the text mode for handling files, which basicaly means that we have using strings which can be edited with a text editor. On the other hand, binary files can not edited with a text editor, but are shorter than text files when storing numbers. The following code is the alternative to the previous one using binary mode.
End of explanation
"""


import pickle
list = ['red', 'green', 'blue']
pickle.dump(list, open('list.dat','wb'))

list2 = pickle.load(open('list.dat', 'rb'))
list2

"""
Explanation: Persistence of objects (serialization) ... in disk
End of explanation
"""


