07.07.2023 Views

Implementing-cryptography-using-python

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 1 ■ Introduction to Cryptography and Python 19

>>> while (count < 5):

>>> print (count)

>>> count = count + 1

>>> else:

>>> print ("The count is greater than 5")

>>> print ("The loop has finished.")

Using Files

In this book, we will be using external files to both read and write. We will

be using the file function, which takes the file location and then performs an

operation. Table 1.9 shows the operations available.

Table 1.9: File Operations

OPERATOR

R

DESCRIPTION

Open text file for reading. The stream is positioned at the beginning of

the file.

r+ Open for reading and writing. The stream is positioned at the beginning

of the file.

W

Truncate file to zero length or create text file for writing. The stream is

positioned at the beginning of the file.

w+ Open for reading and writing. The file is created if it does not exist,

otherwise it is truncated. The stream is positioned at the beginning of the

file.

Append

Open for writing/appending to the file. The file is created if it does not

exist. The stream is positioned at the end of the file. Subsequent writes to

the file will always end up at the current end of file.

a+ Open for reading and writing. The file is created if it does not exist. The

stream is positioned at the end of the file. Subsequent writes to the file

will always end up at the current end of file.

An example we will be using later in this chapter is the following:

>>> # Python 2.7

>>> f=file('dictionary.txt', 'r')

>>> words = [word.strip() for word in f]

>>> f.close()

>>> # Python 3.5

>>> f = open('dictionary.txt', 'r')

>>> words = [word.strip() for word in f]

>>> f.close()

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!