Opening a file with Python

Introduction

All right, you must be crazy to start writing code. And so do we. So let’s get started. :wink:

Only a small note before proceeding: We haven’t had many comments so far in the previous tutorials – which may be for two reasons: either you’re not liking it, or you haven’t had any doubts. Let’s believe it’s for the second reason. :slight_smile:

image

And we will continue – reminding you that our methodology is different, and it is very important that you follow every tutorial and practice – leaving no doubt for later.

Python is one of the most powerful programming languages. And at the same time, it’s one of the easiest to learn. And yet, Python is very likely to continue to grow more and more.

But there are so many resources available for those who want to learn, such as books, handouts, courses, online documentation etc. that it is even difficult to know where to start! :frowning:

And that’s why we’re here to help you. However, you need to know that we are not “just another Python course” … Quite the contrary, we want to be with you with each new tutorial, evolving – when you less realize, you will already master Python, and literally having no limits in your projects and career.

Here we go straight to the point, through examples – which we believe is the best way to learn.

What are we going to do?

Today we will open a text file, read the information that is in it, and present it on the screen. And then close the file.

Even if you never programmed, don’t worry. And also don’t worry about trying to play immediately on your computer – you can always go back to any tutorial and practice - and of course - ask your questions. The most important part is to understand the idea!

Tip: Don’t follow this tutorial with the thought of learning this specifically that we’re going to show you, but how Python allows it, and how you can apply it to other applications you can do. And this tip applies to all the tutorials you will follow with us!

Programming Logic

One thing you need to understand: we never started writing the code directly!

If you don’t even know where to start, you don’t know what to do. Or even if you do. The first thing is always to create the programming logic.

Everything needs an order, an organization. Trying to learn only by code directly is like learning grammar rules without knowing how to read and write. :slight_smile:

Simply, programming logic is: how would I manually solve my problem? And then just “translate” it to Python.

So let’s do the first thing we’ll do in any solution: enumerate the steps we have to do manually.

And let’s get started by learning: Python uses the # character as a comment indicator, or something that will be ignored when executing the code.

Therefore, let’s write our steps, and already include the Python comment character.

  • # step 1: open the file
    
  • # step 2: read the file
    
  • # step 3: show the contents of the file
    
  • # step 4: close the file
    

Okay, the hardest part’s over. The hardest part is not writing code in Python, but understanding and writing what you need to do – as we’ve done above.

With our programming logic created above, now just translate to Python – and believe me, it’s going to be simple. :wink:

Creating our project

To start, we will create a “telecomHallPython” project in our “C:\Hunter\py” directory (1). (Remember that you can choose any other names/directories.) Let’s choose the option of “New environment using: Virtualenv” (2), and make sure that the location (3) is the same where we will store our project.

image

Note: we’re using PyCharm here. But you can use Jupyter Notebook or any other IDE you want, like VSCode.

All right, we’re all set to start writing our Python solutions. :wink:

We’re going to need a sample file, so we’ve created a “Sample.txt.”

image

And we created this file within the directory of our project - like we’ve see how to do it in previous tutorials (You can also create the file through PyCharm or Windows Explorer).

image

image

Tip: Python can access files anywhere, it doesn’t have to be inside the project folder. But we put it here to make it easier to demonstrate.

And to conclude, we created our Python file – we call it “OpeningFile.py”, which is the file where we’re going to write Python code.

image

Writing the code

We then have our recipe, our roadmap with the steps we must follow.

So we can paste these steps into our file.

image

step 1 - open the file

Python has several functions for opening, closing, creating, reading, updating, and deleting files.

But one moment: what is a function?

You can understand how code groups do something. Functions are a common feature among all programming languages, not just Python.

Developers can write blocks of code (functions) that perform specific tasks. And whenever you need to use them, just “call” the desired function.

And when a function is called, we should also inform what it will work with – or the arguments. Some functions do not require an argument - in this case, we consider it as argument = none.

For example, if we are going to call a file open function, we need to enter the file name. In that case I have a mandatory argument, or required.

There are also optional arguments, or arguments that you may or may not use, usually for a more specific use of the function.

But all this we will see in time. For now, just understand that there are functions (code groups) that do things, and for that they need to receive some input.

And in addition to the functions you can write, Python already comes with functions within it – they’re the built-in functions.

And it’s these functions that we can use directly.

In this step, we are opening the file. So let’s have a function for that.

Do you have any idea of the name of the Python function used to open a file? :wink:

If you thought about “open” then you got it right. And as it is a function we put the parentheses at the end: open().

In my programming logic the code would be:

Open ‘Sample.txt’ file

So in the code it gets (see how intuitive Python is):

open('Sample.txt')

image

But if we run that code, we still can’t do anything. That’s because it is in “somewhere in the computer’s memory”. And to be able to “work with” the file, we need to assign it to a variable – which in this case we call “Object”.

An object has a number of attributes. Such as a table: it has width, length, height, color, etc.

Similarly, the objects we can create with Python have attributes or characteristics that we can access, or query.

To assign this open file that was “somewhere in computer’s memory” to a variable/object (“MyFile”) that we know and then we can work with, we use the following code:

MyFile = open('Sample.txt')

From now on our file is “loaded” into the “MyFile” variable (object). And we can, in the code, call several attributes of this variable.

But here we have another tip.

We already know that Python is used by millions of people. And they all realized that the more standardized and intuitive the codes were, the easier it would be, for example when they needed to share a code with someone else – making it even easier to read.

These are “informal” rules, which end up being used by everyone.

For example, virtually all developers, when they assign a file to an object, they call that object as “f.” So let’s do the same, and our code actually looks like this:

f = open ('Sample.txt')

Now, at this point, we have the “Sample.txt file” open (or assigned) to the “f” variable. And we can from this point call our file as “f”.

Tip: Making an analogy with the files we open in our computer, at that point the file is open, as if we had double-clicked on a Word file in Windows Explorer.

So let’s move on.

Being a little more technical, and just to complete the explanations of the open() function, it has two parameters: file name and mode.

There are four different methods (modes) for opening a file: Default “r” (read), “a” (append), “w” (write), and “x” (create).

In addition, in Python you can specify whether the file should be treated as Text or Binary mode: Standard “t” (text), “b” (binary) for example images.

So our code:

f = open ('Sample.txt')

It’s exactly the same as:

f = open('Sample.txt', 'rt')

Because Python understands that we omitted the arguments because we wanted to use the pattern. “r” because we will read the file, and “t” because it is a text format file.

But don’t worry about remember everything for now.

You can always use several resources - including online searches - for more details about the commands you can use. Everybody in the World does this – no one can memorize all the arguments of all functions. :wink:

Just understand that, in conclusion: we used the Python built-in function to open a file, and we obtained a file object.

image

Tip: Python uses single quotes (’) or double quotes ("). You can choose how to use!

step 2 - read the file

Continuing our analogy with an open text file in Word, now that we have the file open, we can do a few things with it. For example, we can read everything at once (all the contents of the file), or read line by line – which is the most normal when we humans do in Word. :wink:

It is important to note, however, that we already have some differences – for example in Word we can edit, or add text at the end (append). In our case, we open the file in Standard mode “r” (read). So we’re just going to be able to read. But this is what we want, so let’s move on.

When we need a function to “open” file, what was the name? “open”!

And now we need a method to “read” the file. Do you have a guess about the name? :wink:

Yes, we use the “read” method.

Important: When we want to access the attributes of an object, we type the object name followed by “.” and then what we want.

In this case, our object is the “f”. So to read our object we use the following code:

f.read()

Notice that Python is simple and very intuitive, you just need to know (understand) what to use. :blush:

step 3 - show file content

We’ve seen how the file can be read. And to demonstrate, let’s ask Python to: show us what it read from the file. So we use the following code:

print(f.read())

image

Running the code, we have the expected result:

image

That is, we have already achieved what we wanted: see the contents of our file!

But of course, there are other methods to read the open file with the open() function.

We use the read(), which reads the entire file at once.

But what if we just wanted to “read a line”?

Again, what’s your guess? :wink:

That’s right: readline().

So:

f = open ('Sample.txt')
print(f.readline())

And the result - only one line was read (and shown). (1)

image

Every time we have the readline code, we move to next line.

f = open ('Sample.txt')
print(f.readline())
print(f.readline())

In this case, reads (and shows) two first lines. (1)

image

In addition to the readline(), you can use the readlines() method. The difference is that it reads all the lines of the text file and remakes them as a string list. (Don’t worry about what string is now – we’ll see more about them soon).

image

And there are other ways of working (manipulating) files, for example with the use of loops. But let’s leave this for a next tutorial.

For today you have seen enough concepts – and once again we highlight – the most important thing is to know how to do, or rather, what can be done. Then just go after the right code to do everything you need.

step 4 - close the file

To conclude for today, we’ll do what you do when you’re done reading what you needed in your Word file – close it.

And now, and for the last time: what is the guess of the code (method) to “close the file”? :wink:

Yes: close(). :blush:

It is a good practice to always close the file when you are done using it. Especially when you are editing files because and in somecases, due to buffering, changes made to a file may not appear until you close the file.

f.close()

At that time, the file - which was stored in our variable “f” was freed from memory.

Running the code

So the complete code of our solution today is this:

image

And the result, is as expected: we can see the contents of the file (1).

image

Notice that in fact, if we disregard the comments, our code is:

image

That is, in just 3 lines of very simple code we were able to complete our first project in Python!

Although simple, with the demo you just saw (and learnt), you probably have realized how powerful Python is!

Follow us, and with our unique learning methodology you will be very soon creating your own Python
Solutions to solve your day-to-day problems!

Download

You can download the files for this tutorial here: Opening a file with Python.zip (506 Bytes)

Conclusion

Today we created our first Python solution.

We saw how to use the open() function with ‘r’ mode to open a text file for reading. We use the read(), readline() and readlines() method to read a text file. And we saw that we should always close a file after completing the reading using the close() method.

But the most important is that we’ve come to know how powerful and at the same time simple Python is and can be used to help us to solve all our problems and challenges.

Continue following the tutorials – and especially, participating. We need to know if you’re getting to follow, and what you’re thinking of this new way of learning Python we’re presenting – even for you who’ve never written any lines of code. :wink:

We look forward to your comment, in this and other tutorials already available, so that we know if we can improve and even direct the new tutorials. :blush:

Index

Back to main index: Data Science by telecomHall Community

1 Like

Thanks! Very well written…smooth… it’s like learning Python by story telling! Thanks for the effort.

Nice explanation, one little doubt before closing file no need to save it :slight_smile:

Not in this case, because we are only “reading” the file - “r” argument.

A good practice, that we’ll see in later is to use with to make sure that the file will be closed when you are finished writing to it.

As in this example, where we are writing (‘w’) to a file:

with open('SampleWrite.txt','w') as f:
   f.write("Here I am writing in the file\n")

This code will create a new file named SampleWrite.txt in the current folder if it does not exist. You need attention here because if that file exists, it is overwritten.

In this code we also can see the use of newline characters, to distinguish different lines.

Request to kindly also let us know the following in the following sessions

how to add/delete/edit content to the file with any occurance of a condition

How to copy content and paste it in excel