PYTHON INTERMEDIATE’S GUIDE |WORKING WITH FILES – PART II

Heyyyy, How is it going? In the last lesson we discussed about the os module and one of its functions which will help us work with files in Python. If you haven’t read that article, you should probably go and have a look at it: PYTHON INTERMEDIATE’S GUIDE | WORKING WITH FILES – PART I, because it is important to know about the os module before we go any further.

So, today we will learn about, how to read and write to text files. But before making any changes to a file, we must open the file in Python. So let’s understand it first.

OPENING A FILE:

We use the open() function in Python, to open a file and be able to make changes to it. The open() function accepts two parameters, The first one being the file path of the file and second one being the mode in which you want to open the file. (BTW if you don’t know what a file path is, feel free to check out my article on file paths <link>)When we use the open() function by specifying the file path to the file, Python opens the file and is now waiting for further instructions.

Now you can open a file in Python in three basic modes: read, write or read & write, for which you can use ‘r’, ‘w’ or ‘w+’ respectively as the second parameter in the open() function.

‘r’

Opens a file for reading only.

‘w’

Opens a file for writing only.

‘w+’

Opens a file for both reading and writing.

‘a’

Opens a file in append mode.

 

Syntax: open(<file_path>, <mode>)

Example: open(‘c:\Users\Noob Code Pro\Desktop\Hello.txt’,’r’)

Note: Both of these parameters must be entered in the form of a string, i.e. using single/double quotes.

WRITING TO A FILE:

This is how you open a file in writing mode:

Syntax: file_object = open(‘<filepath>‘,’w’)

Example: my_file = open(‘c:\\Users\\Desktop\\Programs\\hello.txt’,’w’)

Where, file path is the location of the file inside the computer and ‘w’ is the mode in which you want to open the file which in this case is ‘write’ mode.

This function will return an object, so you have to store it in a variable.

Note: If you try to open a file that doesn’t exist in the specified file path, Python will create a file with that name automatically. For example,

write() FUNCTION:

So, you have opened the file in write mode, now you want to write something to it. This is where we use the write() function.

Syntax: file_object.write(‘<text>’)

Example: my_file.write(‘Hello, World!’)

Note: When you use the write mode to edit a file, if there is any text in that file already, it will be replaced with the new text. So basically, when you use the write mode to write to a file, you will lose the contents of the file. To solve this you can use the append mode instead of the write mode which adds the new text to the old file while preserving the old contents.

READING A FILE:

If you want to just read a file and not make any changes to it, you can use the read() function.

Syntax: file_object = open(‘<filepath>‘,’r’)

Example: my_file = open(‘c:\\Users\\Desktop\\Programs\\hello.txt’,’r’)

 

read() FUNCITON:

Using the read() function you can see the contents of the file but cannot make any changes of your own.

Syntax: <file_object>.read()

Example: my_file.read()

Note: You can only call the read() function on a file once, each time you open it, so you should save the file contents in a variable or a container if you want to use it later.

READING AND WRITING TOGETHER:

You can read and write to a file at the same time using the read and write mode. Other than its method of opening a file, it has no other syntax or rules than the ones already discussed above for reading and writing to a file.

Syntax: file_object = open(‘<filepath>‘,’r’)

Example: my_file = open(‘c:\\Users\\Desktop\\Programs\\hello.txt’,’r’)

APPEND MODE:

If you want to write to a file without overwriting the contents already in it, you may want to use the append mode instead of the write mode. To open a file in append mode, pass ‘a’ as the second parameter in the open() function.

append() FUNCTION:

This is the function that appends/adds a text to a file.

Syntax: <file_object>.write(‘<text>’)

Example: file.write(‘I am a self-taught programmer !!!’)

CLOSING A FILE:

If you open a file using open() method you must close the file using the close() method because if the file is left open Python it could create various problems in a file.

When you have a small program, which works with just one file, closing it will seem as a problem. But when you are working with several files at the same time, closing all of them could be a pain in the as....head. So you could use an alternative method to open and close the file using the with() function.

with() FUNCITON:

If writing the close statement every time after opening a file is hard. Python offers another method:

            Syntax: with open(file_name,mode) as variable_name:

                                    your_code

Example: with open('c:\\users\\Noob Code Pro\\Desktop\\Programs\\test.txt',’w’) as my_file:

                                    my_file.write(‘Hello, self-taught programmers !!’)

This works the same way as the methods discussed before but this is far more efficient. Let’s break this code down, I want you to think of the with() statement as a loop or a conditional statement (remember those?? If you don’t, you can check these out: For LoopsWhile Loops, and Conditional Statements). In the with() statement, Python opens the file in write mode and stores it in a  variable named ‘my_file’. Python keeps it open as long as the code inside the with() statement is executing as soon as Python comes out of the with() statement, it closes the file, thereby eliminating the need of using the close() statement.


CONGRATULATIONS !!! You now know how to read & write to text files in Python. This was one of the coolest things I learnt when I started learning Python and I am really glad to share this knowledge with you. Like I always say, Have fun with it !!! Create some cool programs. Good luck !!!!   

Let me know, if you loved it, hated it, want to kill me or any other sort of feedback in the comments section below. Also, if you have any queries regarding the topics taught in this lesson or previous lessons, you can always find me in the comments section below or in the telegram channel where you can personally talk to me and ask me any question about anything we have learnt so far.

So, this was how to work with  files using Python. Stay tuned for another article next week, same time, where we will learn to work with another kind of files, CSV files. So more cool stuff coming your way, DON’T MISS IT !!


I hope this article answered all of your questions and even helped you in becoming a better programmer. IF IT DID, leave a like AND FOLLOW THIS BLOG TO BECOME A PROFESSIONAL PYTHON PROGRAMMER FROM A TOTAL BEGINNER. IF IT DIDN'T feel free to ask any further queries in the comment section below.


If you are a beginner, intermediate, advanced or just someone interested in programming, feel free to join our telegram channel and be among people like you:


And do you know the best part? Joining it is FREE !!!

So go ahead click on the link and I will see you there. 


 HOPE YOU HAVE AN AWESOME DAY AHEAD !!! 

Post a Comment

0 Comments