Are the Files Suppose to Be With the Py to Read

In this guide I will show you how to use the with argument to simplify the mode yous open and handle files in your Python programs.

The with statement creates a context director that simplify the way files are opened and airtight in Python programs. Without using the with argument a developer has to remember to close file handlers. This is automatically done by Python when using the with open up…as blueprint.

We will start by opening a file without the with argument and then we will meet the advantages of doing it using the with statement.

Let's get started!

Opening a File in Python Without Using the With Statement

I have created a file called output.txt that has the post-obit content:

          $ true cat output.txt  Line1 Line2 Line3 Line4 Line5                  

Let'due south accept a wait at the definition of the open function from the Python documentation:

Python Open Function

In this guide nosotros will focus on the first 2 arguments of the open function: file and manner.

Here is how we tin open up our file in read manner using the open function.

Read manner is the default one.

          >>> f = open('output.txt') >>> f.read() 'Line1\nLine2\nLine3\nLine4\nLine5\n' >>> f.close() >>> f.closed True                  

Nosotros use the open role to create a file handler (f) and and then we use the file handler to read the content of the file using the read() function.

After reading the content of the file we use the close() function to close the handler.

Running f.airtight nosotros get back True as a confirmation that the file handler is airtight.

Let's meet how the file object in the previous case looks similar:

          >>> f = open('output.txt') >>> impress(f) <_io.TextIOWrapper name='output.txt' mode='r' encoding='UTF-8'> >>> print(f.__dict__) {'mode': 'r'}                  

It's of type TextIOWrapper, its default encoding is UTF-8 and information technology has an attribute called mode.

To find out the methods y'all tin utilise on this file object run the following command in the Python crush:

          >>> help(f)        

Note: Read mode is the default mode used past Python to open files unless you lot laissez passer a second parameter to the open up office (encounter some examples below):

Mode Case
r (read – text format) f = open(filename, 'r')
rb (read – binary format) f = open(filename, 'rb')
due west (write – text format, truncates the file) f = open(filename, 'w')
wb (write – binary format, truncates the file) f = open(filename, 'wb')
r+ (read and write – text format) f = open up(filename, 'r+')
a (append – text format, appends to the cease of the file) f = open(filename, 'a')

How to Read a File Using With Open…As in Python

Let'south encounter what happens if nosotros use the with statement when opening files in Python.

The syntax we will employ is:

                      with open up(file, mode)            as            file_object        

When using the with argument a file is automatically closed when it's non needed anymore. This is confirmed past the fact that in the following code f.closed returns True.

          >>> with open('output.txt') as f: ...     information = f.read() ...  >>> f.airtight True                  

Immigration resource on your organisation is extremely important. Imagine if you create a program that opens hundreds of files and doesn't shut them. For how long it can go on before using all system resource?

So, to recap…

If you don't employ the with keyword you have to remember to phone call f.close() to free up resources once yous don't need your file anymore. Running f.close() is non required when using the with argument.

What happens if we try to read a file that has already been closed?

          >>> f.closed True >>> f.read() Traceback (virtually contempo call terminal):   File "<stdin>", line one, in <module> ValueError: I/O performance on closed file.                  

Python raises a ValueError exception.

Print All the Lines in a File Using With Open…Equally

Allow'southward find out how to print all the lines in a file after opening the file with the with statement.

Nosotros volition utilize the file output.txt used in the previous instance and loop through the lines in the file one at the time:

          with open('output.txt', 'r+') every bit f:     for line in f:         print(line)                  

I have passed r+ as 2nd parameter to open up the file for reading and writing.

Equally yous can see I'm using a for loop to go through the lines of the file using the file object.

          $ python with_open_example.py  Line1   Line2   Line3   Line4   Line5                  

For some reason, the print argument is calculation new line characters that are not present in the original file.

To go rid of them you can utilize the post-obit syntax:

          print(line, stop='')        

Our lawmaking becomes:

          with open('output.txt', 'r+') every bit f:     for line in f:         print(line, finish='')  [output] $ python with_open_example.py  Line1 Line2 Line3 Line4 Line5                  

Looks good at present 🙂

Open Multiple Files in a Single With Statement

Imagine you have to write a program that takes a single listing of strings and writes each cord in one of two files.

For example, let's say we accept the following list:

          items = ['canis familiaris', 'cat', 'apple', 'pear', 'lion', 'banana']        

And our program has to write animals to a file called animals.out and fruits to a different file chosen fruits.out.

Here is how y'all would exercise information technology using two open statements in a single with expression:

          items = ['domestic dog', 'cat', 'apple', 'pear', 'lion', 'banana']     with open('animals.out', 'w') equally animals_f, open('fruits.out', 'due west') equally fruits_f:     for item in items:         if detail in ['canis familiaris', 'cat', 'lion']:             animals_f.write(item + '\due north')           if item in ['apple', 'pear', 'banana']:             fruits_f.write(item + '\n')                  

Permit'due south run the program and confirm that the two files are created as nosotros expect:

          $ python with_open_example.py  $ cat fruits.out  apple pear banana $ cat animals.out  dog cat king of beasts                  

To be able to use two open statements in one with expression Python 2.7, Python 3.1 or newer are required.

Using Nested With Open Statements in Python

Information technology's as well possible to nest with open statements instead of using two open up statements in the same line.

Hither is how we tin can update our previous program using two with nested statements:

          items = ['dog', 'true cat', 'apple', 'pear', 'king of beasts', 'assistant']     with open('animals.out', 'w') every bit animals_f:     with open('fruits.out', 'w') every bit fruits_f:         for detail in items:             if item in ['dog', 'cat', 'king of beasts']:                 animals_f.write(item + '\due north')               if item in ['apple tree', 'pear', 'assistant']:                 fruits_f.write(item + '\north')                  

Below you lot tin meet that program still does what information technology'southward supposed to do 🙂

          $ python with_open_example.py  $ cat fruits.out  apple pear banana $ cat animals.out  domestic dog cat lion                  

Using Python With Open to Work with Binary Files

We often piece of work with text file, simply what about binary files?

For instance, how would you open up a PNG file using what we have learned about the with statement?

In the current directory I have downloaded a moving-picture show called python.png:

          $ ls -ltr full 208 -rw-r--r--@ ane myuser  mygroup  102916 22 Feb xx:13 python.png                  

We already know that its size is 102916 bytes from the output of the ls command above.

Let's open up it and confirm its size in Python.

How practice nosotros become the number of bytes in the file using Python?

          with open up('python.png', 'rb') as png_file:     bytes_count = 0      while png_file.read(ane):         bytes_count += 1  print("The size of the file is: {}".format(bytes_count))                  

Here is what nosotros have done in our code:

  1. Use with open…as to open up the PNG file in binary mode.
  2. Read one byte at the time using a while loop until nosotros reach the cease of the file.
  3. Increase the value of the bytes_count integer every time we read a byte.

The output of the plan is:

          $ python read_binary_file.py  The size of the file is: 102916                  

The file size calculated by our program matches the size shown past the ls control. Nice!

Using Try Finally equally Equivalent of With Open…As

To give you a full agreement of the with statement I also want to show you lot an culling mode to write a logic that behaves like with open…every bit.

We will use a try…finally statement to brand sure the file object is always closed later on executing the try code block. I desire to write something similar to the following:

          >>> with open('output.txt') equally f: ...     data = f.read()        

Hither is the code:

          >>> f = open('output.txt') >>> try: ...     data = f.read() ... finally: ...     f.shut() ...  >>> f.closed True                  

Tin you lot see the reward of using with open instead?

It definitely makes our code more curtailed. Imagine if we had to use try…finally statements for each file we open up!

Conclusion

In this simple guide we have seen how to use with open in Python to simplify the fashion nosotros work with files.

Practice its syntax few times and yous volition remember it without bug whenever you will need to employ it in the future.

I take besides written a tutorial almost executing crush commands in Python and in one of the sections I show how to employ the with argument to write the output of a command to a file.

Have a look at it to strengthen your Python core skills when working with the Operating System.

Related posts:

Share knowledge with your friends!

aubetarm2000.blogspot.com

Source: https://codefather.tech/blog/python-with-open/

0 Response to "Are the Files Suppose to Be With the Py to Read"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel