📱

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, but 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. Therefore, after opening a file and working with it, you should always close it.

Now, let's 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." You may notice that I don't have this file in my project right now. 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," followed by a slash, and then the name of the file you want to create 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 specifies 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 covered in detail.

At this point, we have indicated that we are opening a specific file and specified 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 "close" function on the file variable. 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 you want to perform 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 call the "write" method. This method allows us to write a string of text inside the file. You can put any text you want here. Let's just write "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 write multiple lines of text, you can call the "write" method multiple 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 tells Python to move 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 text. Each time, the file is opened, all previous information is erased, and new information is written in its place. This happens because we are using the "write" method, which opens the file for writing. 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 information, we need to use the "a" mode, which stands for "append." It works the same way as the previous mode, but this time, new information will be added to the existing information.

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. I 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 now and type "Hello World," the program will finish, and 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 type "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 call the "open" function and specify the file I want to open, which is "text.txt" in the "data" folder.

Now, 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 immediately after opening it to avoid any issues.

Now, let's try to read the file. I will call the "read" function on the file variable. 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 calling the "read" function without any parameters returns the entire text from the file.

We can also pass a number as a parameter to specify how many characters we want 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."

I can also specify 20, and it will return the first 20 characters. If we want to read the entire text, we use "read" without any parameters. If we want to read a specific number of characters, we pass that number as a parameter.

If you need to read the file line by line, we can create a loop. I will create a variable called "line" and iterate through the file. I will comment out the previous print statement to avoid additional output.

Now, I will print the variable "line." When we run this, we will see that all lines are 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.

Now, everything works as expected.

To summarize, when reading a file, you can use either the "read" function and specify the number of characters you want to read, or you can use a loop to read line by line.

This concludes our lesson. We learned 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, always close it.

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

That's all for now! See you in the next lesson. Goodbye!