📱

Get Our Mobile App

Take your business learning on the go!

Download on the App StoreGet it on Google Play

Уроки Python с нуля / #13 – Работа с файлами за счет Питон

Школа itProger / Программирование13:17

Transcription

Hello! In this lesson, we will learn how to create, read, and write information to files using Python.

Before we begin, I would like to recommend the website itprager.com. On this site, you will find homework assignments and a lot of other useful information. The link to this lesson on the site will be in the description of this video.

In Python, there are different functions for working with files, and you need to remember a few important points.

First, any file you want to work with must be opened initially. There is a specific function for this. After opening the file, you need to perform some action with it, such as reading information from it or writing information to it. Finally, after working with the file, you must always close it. This is an important point because many people forget to close files, leading to memory leaks. If you don't close files and open, say, 10 files without closing them, your program will become overloaded because it will consume resources to handle each open file. Consequently, you will experience memory leaks.

So, after opening a file and working with it, you should always close it. Now, we will learn how to do all of this using Python.

To start, let's try to open a file. First, I will create a variable, which I will call "file." The name can be anything; for example, I will name it "my_file." I will store the opened file in this variable, and I will work with the file through this variable.

Next, to open the file, I need to use a function called "open." This function takes several parameters. We will specify the first parameter, which is the name of the file I want to open. Let's assume I will open a file named "text.txt."

At this point, you may notice that I do not have this file in my project. If such a file does not exist in your project, it will be created automatically. If you want the file to be created in a specific folder, you can specify the folder name here, for example, "data." Then, you add a slash and indicate that the file will be created in that folder.

Let's create such a folder, and the file will be created automatically inside this folder. I will name the folder "data," and all files will be stored inside it.

After specifying the file we need to open, we also need to indicate a second parameter, which is the mode for opening the file. There are different ways to open a file: you can open it for reading, for writing, or simply to create it.

We will use a mode called "w," which means we are opening the file for writing. Information about other modes is available on the itprager.com website. I will leave a link to this lesson on the site in the description of this video. There, you can find a convenient table listing various formats. Some of them we will study now, while others are rarely used and will not be included in this table.

So, at this point, we have specified that we are opening a specific file and indicated the mode for opening it. We are opening it for writing information inside it.

Next, I always recommend closing the file immediately after opening it. To do this, we simply call the file variable and use the "close" function. If you forget to close the file, you will experience memory leaks, so it's better to do this right away.

Between the "open" and "close" functions, you will write the operations with the file. For example, I want to write some information to the file. To do this, I will again refer to our file variable and use the "write" method. This method allows us to insert a string of text into the file. You can put any text you want here. Let's just put the string "Hello."

For now, we won't add anything else. If we run the program now, we will notice that nothing is printed to the console. This is logical because we haven't output anything. However, inside the "data" folder, we already have a new file, and in this file, the word "Hello" is written. Everything has been processed correctly.

If you want to add multiple lines of text, you can call the "write" method several times. For example, let's add three exclamation marks. If we run this, we will see that "Hello" is followed by three exclamation marks.

You may notice that there is no line break between them, even though we called the "write" method twice. This happens because, unlike the "print" method, the "write" method does not automatically add a newline at the end. If we need a newline, we can add it ourselves using "\n." This indicates that we are moving to a new line.

If we run this now, we will see "Hello" on one line, and the three exclamation marks on a new line. No matter how many times I run the program, the text will not be added to the previous one. Each time, the file is opened, all previous information is erased, and new information is written instead. This happens because the "write" method opens the file in "w" mode, which means it allows us to overwrite the file. If the file does not exist, it will be created, and every time we write information, all previous information is deleted.

If we want to add new information to the existing content, we need to use the "a" mode, which stands for "append." It works just like the previous mode, but this time, new information will be added to the existing content.

So, we had "Hello," followed by three exclamation marks, and now we will add new text at the end. This text will be the same as before: "Hello" and three exclamation marks. If I run this again, we will see that the text is constantly being added.

To summarize, if you want to overwrite a file, use the "w" mode. If you want to append information, use the "a" mode.

Now, let's try something more interesting. Let's allow the user to input information through the console, and then we will add this information to the file. I will create a variable called "data" to store the value received from the user. It will prompt the user to enter text, for example, "Enter text."

I will set the file opening mode to "w" so that all information in the file is overwritten each time. Then, I will use the "write" function only once, placing the user's input inside it.

If I run this and enter "Hello World," the program will finish. If I check the file, everything has been processed correctly.

I would also like to add a newline at the end and use the "a" mode so that the next text is added on a new line.

Let’s run the program again and enter "My program is cool." After pressing enter, we will see that "Hello World" is followed by the new text, and there is a newline between them. Everything is processed correctly.

Now, let's learn how to read data from a file. To read data, we need to use the same logic: we must first open the file, then read the data, and finally close the file.

Let's comment out all the previous lines of code so they don't interfere with our new task. We will now focus on reading data.

I will create a variable called "file" again. The name can be anything, but it makes sense to keep it the same. Next, I will use the "open" function and specify the file I want to open, which is "text.txt" in the "data" folder.

Then, I need to specify the mode for opening this file. We will open the file for reading, so I will use "r," which means we are opening it for reading.

Again, I recommend closing the file at the end to avoid any issues.

Now, let's try to read the file. I will use the "read" function. Let's run this and see what happens.

Of course, nothing will happen because I forgot to print the output. Now, if I run it, we will see that the "read" function returns the entire text from the file.

We can also pass a number as a parameter to specify how many characters to read. For example, if I specify 1, it will return just one character, which is "H." If I specify 4, it will return the first four characters, which are "Hell."

If I specify 20, it will return the first 20 characters. So, if you want to read the entire text, use "read" without parameters. If you want to read a specific number of characters, specify that number.

If you need to read the file line by line, you can create a loop. For example, I will create a variable called "line" and iterate through the file.

I will comment out the print statement to avoid additional output. Now, I will print the variable "line."

When we run this, we will see that each line is printed, but there is an extra space between them. This happens because when we read each line, there is a newline character at the end of each line, and the print function adds another newline.

If you don't want these extra spaces, you can use "end=''" in the print function to avoid adding an additional newline.

For reading a file, you can either use the "read" function and specify the number of characters you want to read, or you can use a loop to read one line at a time.

In conclusion, this lesson has taught us how to work with files in Python. Remember a few key points:

First, always open the file and specify the correct mode. After working with the file, you must always close it.

If you follow these three simple points, you will be able to work with any files using Python.

That's all for now! I look forward to seeing you in the next lesson. Goodbye!