A rather important use of Python in the cybersecurity space
is to automate the handling of files.
I may be retrieving information in a log file,
malware analysis,
reading in the CSV file to process work or many
other automation‑inspired reasons.
Before being able to read from or write to a file in Python,
you must first open it with the open function,
which includes the location, name of the file,
and method or mode for how you want to handle the file.
The r mode is the default if no mode is specified and
opens the file in read‑only mode.
This gives you access to see what is inside the file,
but not overwrite or add to the file.
An error will be returned if the file is not found at the location specified.
The Python language does have a try/accept feature that allows you to
gracefully handle the exceptions if the file is not found.
W mode opens the file for writing, but not at the end,
but rather at the beginning, meaning if the file already exists,
it will erase and overwrite the file.
In the case the specified file is not found, it will simply create it.
An item of note here is that it does not wait until the first write to erase it,
simply opening the file with w mode will erase the previous content.
A mode is an append mode, again allowing you to write to the file,
but this time starting at the end and not overwriting the file.
Adding a plus on the end of the mode allows you to
both read and write to the file,
but the w+ mode also overwrites the file to start,
allowing you to write new content and then also
allowing you to read it back later.
X mode creates a file if it does not already exist,
but returns an error if it does.
This is useful so you don't accidentally overwrite a file when
creating it. Adding a +b on the end of the mode chosen will allow you
to read or write in binary instead of text.
Once the file is open in read mode,
you have a few options on how to read in the lines.
The read method will read the number of bytes specified.
If no bytes are specified, it will read in the entire file.
The readline method reads in the file one line at a time,
whereas the readlines method reads in the entire file up to
the specified number of bytes called in the parameters and
drops it into a series of lists.
If no byte count is specified, it will read the entire file.
The write method will add content from the start of the file.
Each additional write called in the script will continuously
append to the end of the previously written line.
The writelines method will write all the content of the list to the file.
It is important to note that subsequent writes will
continue on the same line previously left off. If you want
every write to start on a new line,
be sure to add /n to the string about to be written.
We will talk about how to delete files once we discuss the OS library,
which we'll get into in the next module.