Python File Read

Python File Read - read() method

Python has a function to read files. The read() method is one of the inbuilt Python File method which is used to read file objects.

The read method is used on the return value of open () method in Python.

Syntax: read(size)

  • size‘ parameter is an optional parameter. If specified, the read() method will read the number of characters equal to size.
  • Default value of size and is -1 and if the value of size is set to negative or zero, the read() method will iterate the whole file.

To read the contents in a file, you have to call the read() function on the file object of that file.

Example

Python File Read method

Let’s understand the code:

  1. There are different modes in which you can open a file. By default, the mode of open() method is the read mode so we did not specify it in the example.

    You can set different modes to specify if you want to read or write into the file in Python.

  2. Then we access the read() method using the dot separator. After reading the file, it is always recommended to close it using the close() method.

Well, this is not the only method that acts as a file reader in Python. You can also use readline() method to read the file line by line in Python.

Python File readline () method

Python file readline() method reads only a single line from the file. We are going to add some extra lines in our example.txt file. Let’s see this function in action.

Example

Python readbyline() method

Bonus Tips

At the end of each line or string in the file, readline() method returns a ‘\n‘ (newline) character. This newline character is not added at the end of last line.

Python File Read - Looping over file object

There is even a better way to read from a file other than the two methods described above. Looping over the file object results in simpler code and better memory efficiency!

Example

Python looping over File Read

You can decide the number of times you want to run the loop. This will specify the number of lines you want to read from the file without having much information about the methods.

Tutorials for all brains!