MD4 Work with files Python: Access a text file in Python Flashcards

1
Q

SEE COURSE 7 MD4 VIDEO

file:///Users/rikkpaul/Desktop/Cyber%20Security/VIDEO%20LINKS/COURSE%207%20MD4/index.webm

A

Security professionals are often tasked with reviewing log files. These files may have thousands of entries, so it can be helpful to automate this process, and that’s where Python comes in. Let’s start by importing a simple text file that just contains a few words and then restoring it as a string in Python.

All we need is the text file, its location, and the right Python keywords. We’re going to start by typing a “with” statement. The keyword with handles errors and manages external resources. When using with, Python knows to automatically release resources that would otherwise keep our system busy until the program finishes running. It’s often used in file handling to automatically close a file after reading it. To open files and then read them, we write a statement that begins with the keyword with. Then, we use the open() function.

Open() is a function that opens a file in Python. The first parameter is the name of the text file on your computer or a link to it on the internet. Depending on the Python environment, you might also need to include a path to this file. Remember to include the .txt extension in the file name.

Now let’s discuss the second parameter. This parameter in the open() function tells Python what we want to do with the file. In our case, we want to read a file, so we use the letter “r” between quotation marks. If we wanted to write to a file, we would replace this “r” with a “w”. But here, we’re focusing on reading.

Finally, file is a variable that contains the file information as long as we’re inside the with statement. Like with other types of statements, we end our with statement with a colon. The code that comes after the colon will tell Python what to do with the content of the file.

Let’s go into Python and use what we learned. We’re ready to open a text file in Python.

Now we’ll type our with statement.

Next, we’ll use Python’s built-in read method. The read method converts files into strings. Now let’s go back to our with statement. Similar to a for loop, with statements start an indent on the next line. This tells Python that this code is happening inside the with statement. Inside of the statement, we’re going to use the read() function to turn our file into a string and store that inside a new variable.

This new variable can be used outside of the with statement. So let’s exit the with statement by removing the indentation and print the variable.

Perfect! The string from the text prints out.

Coming up, we’re going to discuss parsing files so we are equipped to handle security logs in the future.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly