Python Basic – How to Work with Files in Python

Home /

Table of Contents

File Handling

File handling in Python allows you to work with files on your local computer. It enables you to create, open, read, write, and close files, as well as to manipulate file paths. File handling is an important aspect of any programming language. Python allows for reading and writing data to and from files, which can be used to store and retrieve information permanently. With file handling, one can perform tasks such as reading from a file, writing to a file, creating a new file, and so on. The ability to handle files is important for a wide range of applications, including data storage, backups, automation, and more. By using file handling in Python, one can manage files and data more effectively, which is essential for many applications.

File Open in Python

Programming means working with data from files is a very normal phenomenon. And it is very easy to work with files in Python. It is very easy to read data from any file, write new data in the file or update the file content, etc. by writing very little code.

At the beginning of working with the file, you have to open that file using Python’s built-in open function. Open does not mean open to any editor, but to Python, it is open in working mode. This can be done by typing a line like the following –

   data = open("file1.txt")

The path of the file in question has to be given as an argument of the open function. If the Python script and the file are in the same location on the computer, then just type the file name as above. Otherwise

 data = open (“/home/tuhin/Desktop/Problem-Solving/Python/file.txt“).

There are other arguments to open functions such as – passing the second argument to determine the mode in which Python will open the file, just to read data from it, to write data there, or to add new data. For example, to write and to open in the write mode, read mode, and append mode

   data = open("file1.txt", "w") # Write mode
   data = open("file1.txt", "r") # Read mode
   data = open("file1.txt", "a") # Append mode

After opening the file and working on it, another important task is to close the file. Otherwise, the file will remain open to Python for no reason, which will actually occupy the memory and play a bad role in the performance of the program. All in all, we open a file on any computer with an editor and close it at the end of the work so as not to waste unnecessary RAM. For the same reason, it should be closed programmatically at the end of the work.

a there, or to add new data. For example, to write and to open in the write mode, read mode, and append mode

   data = open("file1.txt", "w")
   """
   execting
   some statement
   here
   """
   data.close()


File Read in Python

In the previous section, we saw how to open and close files in Python. In this section, we will see how to open a file and read content from that file in different ways.

ZktsjeAx4c 56YfNkZNX Mb2UHH0sZQy2yFTM8vgYusXEmfpvQJB1Va9VE0OmqihYeuc47ZbvKfWpqYR4XQsqsm9FXTu39er6pjxEew tBQo5ipRm3puC4IVXvR6fODkhVZMMJ85fQ TyK3NPw - Python Basic - How to Work with Files in Python

Open a file and read all the contents of that file and see a program to print on the screen –

Example:

   data = open("file1.txt", "r")
   content = data.read()
 
   print(content)
 
   data.close()

Output:

   Hello EnableGeek!!!
   This is the second line in the file.
   This is the third one.

File Write in Python

Why should the names of Python’s methods be kept in mind? For example, the name of the function to read the file read and even if no one says to write the name of the function to write in the file that you have taken so far. And yes, your idea is not wrong. Read from the file and write in the file, whatever you do, you have to open the file first. Should be closed again at the end of the work (should).

Example:

   data = open("file1.txt", "w")
   data.write("This is a text!!!")
   data.close()
 
   data = open("file1.txt", "r")
   print(data.read())
   data.close()

Output:

   This is a text!!!

The above two parts of the program. In the first part, a line has been written by opening the file. The file with this name already exists according to our current example. But due to opening in w mode and rewriting here, all the previous contents of that file will be deleted and the newly written content will be written. 

If there was no file with that name, Python would create a new file with that name and write it there. The file has been closed after writing.

In the second part, the file is opened again in r mode for reading and all the contents are read and printed on the screen.

Proper work with files

It has already been said several times that it is very important to close the file after working on it. So, some techniques can be adopted or it can be made a habit so that this useful work does not go wrong again and again. 

For example, let’s look at the following program –

Example:

   try:
       data = open("file1.txt", "r")
       content = data.read()
       print(content)
   finally:
       data.close()

In the above program, we have opened and read the file in the try block and closed in the finally block. By doing this, whatever happens, the file will be closed.

There is one more best practice. with the use of statements. Let’s look at an example first and then analyze –

Example:

   with open("file1.txt") as line:
       print(line.read())

Output:

       Hello EnableGeek!!!
       This is the second line in the file.
       This is the third one.

with statement actually creates a temporary variable. In the above program, a temporary variable named line has been created for the open(“file1.txt”) statement using this. In other words, line = open (“file1.txt”). This line can be used in the code that covers with. Again, another interesting thing about using with is that the temporary variables created by it are destroyed as soon as the work of the code block under it is completed. In this way, our purpose is achieved and the work of file closure is done. So far, this is considered the best practice to do short work with files.

Share The Tutorial With Your Friends
Twiter
Facebook
LinkedIn
Email
WhatsApp
Skype
Reddit

Check Our Ebook for This Online Course

Advanced topics are covered in this ebook with many practical examples.

Other Recommended Article