Lesson-14: Python Basic File Operations

Python Basic File Operations

Create The File

For file operations in Python, we will use a function called open (). File name and mode must be specified as parameters. Kip will be discussed in detail in the following sections.

f = open(file_name, mode)

For example, to open a file called “deneme.txt” in write mode, we use the following command:

f= open("deneme.txt", "w")

Here’s the ‘ deneme.txt ‘ indicates the name of our file. the letter” w ” says that this file is opened in write mode.

When this command runs, try to get there in which folder our python file currently exists.creates a file named txt. If the file exists and you have given this command, you should pay attention. Because if you run this command again in W mode, it deletes the file and opens a new one as empty. For this reason, if you are opening the ten file to read it, it will be in your best interest to open it in "r" mode.

By the way, when you type the file name, if you want that file to be somewhere else, you should do this:

f= open("/folder/file_name", "w")

If you type the file name without specifying a directory, the file you created will occur under which directory you are currently located.

We learned how to create an empty file in the Python programming language. Now we can start entering content.

Writing To File

When we open a file in write mode, as shown above, Python will create a hollow file for us. And how do we fill out this file?

In the Python programming language, we can add something to the file that we open in” w ” mode. To do this, we must use the write command.

f.write("Wanted to add...")

Examine the following structure as an example.
f= open("deneme.txt", "w") 
f.write("Entering my first content...")

When these commands are executed , try.”I enter my first content…”information is added.

If that’s the case, you need to close your file. You know we can do this with another method called close() :

We did the following in order:

1- by opening a file called experiment in write mode, we have created a file with this name,
2- we entered some information in this file using the write() method,
3- In order to make sure that the information we write to our file is processed in the file and to release all the resources that the operating system activates to open the file and process the data to the file, we closed our program with the close() method.

By the way, before closing this header, let’s give you another important information. When we open a file in python in “w” mode, if a file with that name already exists in the corresponding directory, Python will delete it without question and create another empty file with the same name instead. I mean, for example, the collection file above.if you create a file named txt and write something in it, and then try to open this file in “w” mode again, Python will delete all the contents of this file and try again.it will create another file named txt. So we pay attention when using this “w” mode during file operations and do not accidentally delete our existing files on the disk.

We have seen how information can be written to a file with what we have described here. Came to read now.

Read File

To read a file in Python, we will use a method similar to the write method we described above. As you know, we use the letter “w” to open a file in write mode. To open a file in Read Mode, we will use the letter “r”.

For example, let’s open a file called “python.txt” that exists on our computer to read:

f_read= open("python.txt", "r")

To open the file in read mode with open, we must open it in “r” mode. So we can just read. So when you don’t specify a mode when opening a file, Python will assume that we want to open that file in Read Mode.

now let’s talk about three different reading methods called read ( ), readline ( ), readlines ().

All three methods above allow us to read files in Python. So, if all three of these methods do the same job, why are there three different methods, not one method?

Although all three of these methods are useful for reading files, the output they give is different from each other. So you may encounter situations where you need to use different methods for different purposes.

The easiest way to understand the difference between these methods is to use these three methods in order and examine the results.

First, let’s assume that we have a file called python.txt, The contents of which are:

Ahmet Özbudak : 0533 123 23 34
Mehmet Sülün  : 0532 212 22 22
Sami Sam      : 0542 333 34 34

Read ( ) method:

Now let’s open a file and write the following codes:


When we run these codes, if the operating system you are using is GNU/Linux, you will probably get the following output:

Ahmet Özbudak : 0533 123 23 34
Mehmet Sülün  : 0532 212 22 22
Sami Sam      : 0542 333 34 34

But if you ran these codes on Windows, the Turkish characters may be corrupted. Ignore this situation for now. In a moment, we will explain the cause of this situation.

What we get above is a sequence of characters you know you can confirm it as follows:

fihrist = open("fihrist.txt")

Readline ( ) method:

As you can see, the read() method gives us the entire contents of the file as a string of characters. Let’s see:

dosya_oku= open("python.txt")

Here we also used the readline() method. These codes give us the following output:

Ahmet Özbudak : 0533 123 23 34

the read () method gave us the entire contents of the file. As you can see, the line() method gives a single line. In other words, with this method, we can read files line by line.
To better see how this method works, you can also run these codes through the interactive shell instead of writing and running them in a file:

>>> dosya_oku= open("python.txt", "r")
>>> print(dosya_oku.readline())

Ahmet Özbudak : 0533 123 23 34

>>> print(python.readline())

Mehmet Sülün  : 0532 212 22 22

>>> print(python.readline())

Sami Sam      : 0542 333 34 34

As you can see, the readline() method actually reads the file line by line.

After a file is fully read, Python does not automatically return to the beginning of the file. In such a case, we will look at how to return to the beginning of the file, but if you want, we will continue with another topic. We will solve this later with seek( ) method.

The ability not to automatically rewind after reading the entire file applies not only to the readline() method, but also to all other file reading methods. In other words, when you read a file using any of the read (), readline (), or readlines() methods, the cursor does not return to the beginning.

As we have said and shown, the read() and readline() methods return us a sequence of characters. The difference between these two methods is that the read() method puts the entire file in front of us, while the readline() method reads the file line by line and moves one line in front of us each time. Let’s see what the readlines() method does…

Realines ( ) method:

Let’s write these codes:

dosya_oku= open("python.txt")

When we write these codes, we will get a printout similar to this:

['Ahmet Özbudak : 0533 123 23 34\n', 
'Mehmet Sülün  : 0532 212 22 22\n',
 'Sami Sam      : 0542 333 34 34']

As you can see, this time we encounter a list instead of a sequence of characters. This means that the read() and readline() methods give us a string of characters as output, while the readlines () method gives a list. Now you must know exactly why this is important information. Because the type of data directly affects what we can and cannot do with that data.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *