MOCKSTACKS
EN
Questions And Answers

More Tutorials









Python Open(), Read() & Readline() For Reading File


As we now have an idea of what files(text or binary) are and their access modes, we are now ready to dive into the discussion of file handling methods. When we want to read or write a file (say on our hard drive), we must first open the file. When we open a file, we are asking the operating system to find the file by name, making sure the file exists.

How to open a file?


Python has a built-in open() function to open a file.

The syntax of the function is:

open("filename" ,"mode")

To open a file, we must specify two things,

Name of the file and its extension
Access mode where we can specify in which mode file has to be opened, it could either be read (r), write (w) or append(a), etc.

For Example,
open("myfile.txt")

The file “myfile.txt” will open in "rt" mode as it is the default mode. But the best practice is to follow the syntax to avoid errors.

The open function returns a file object. We store this file object into a variable which is generally called as a file pointer/file handler. Here is a code snippet to open the file using file handing in Python,
  f=open("myfile.txt," "w"))

You can use this file pointer to further add modifications in the file. An error could also be raised if the operation fails while opening the file. It could be due to various reasons like trying to access a file that is already closed or trying to read a file open in write mode.


How to read a file?


To read a file in Python, there are various methods available,

We can read a whole file line by line using a for loop in combination with an iterator. This will be a fast and efficient way of reading data.

When opening a file for reading, Python needs to know exactly how the file should be opened. Two access modes are available reading (r), and reading in binary mode (rb). They have to be specified during opening a file with the built-in open() method.

f = open("myfile.txt", "r")

The read() method reads the whole file by default. We can also use the read(size) method where you can specify how many characters we want to return i.e.
f.read(2);

You can use the readline() method to read individual lines of a file. By calling readline() a second time, you will get the next line.

readlines() method reads until the end the file ends and returns a list of lines of the entire file. It does not read more than one line.

f=open("myfile.txt","r");
f.readlines() #Returns a list object

Note: The default mode to read data is text mode. If you want to read data in binary format, use ''rb".

Is it necessary to close a file?

The answer is yes, it is always the best practice to close a file after you are done performing operations on it. However, Python runs a garbage collector to clean up the unused objects, but as good programmers, we must not rely on it to close the file. Python has a build-in close() function to close a file i.e;

f.close()


Example


f = open("harry.txt", "rt")
print(f.readlines())
print(f.readline())
print(f.readline())
print(f.readline())
content = f.read()

for line in f:
     print(line, end="")
print(content)
content = f.read(34455)
print("1", content)

content = f.read(34455)
print("2", content)
f.close()


Conclusion

In this page (written and validated by ) you learned about Python Open(), Read() & Readline() For Reading File . What's Next? If you are interested in completing Python tutorial, your next topic will be learning about: Python Writing And Appending To A File.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.