Advertisement



< Prev
Next >



Python - Reading a file on disk




In our last tutorial, we have introduced you to some important file input/output operations that we could perform. In this tutorial, we are going to explain how to read the content of an existing file. But before we read the content of an existing file present on the disk, we must open it. Although we have already discussed how to open a file in Python but for those who have not read out last article, here is a recap.





Let us another program to read a file using the readlines() method, which reads all the lines in a file and returns a list of lines, unless we have passed an integer value as an argument while calling it and in that case it will only read the number of bytes corresponding to the integer value passed to it. Let's read the same file, as we did in the last program - File.txt

File.txt
Hello there!
How are you doing? 
May you have a blessed day!



A program to read a file present on disk
# Python - Reading the content of a file using the built-in open() function and the read() method


# Number of bytes to read
bytes_to_read = 60


# Calling the open() function to open a file named File.txt in read mode
file = open('File1.txt', 'r')


# Calling the readline() method for file objects, to read a single line
print('readlines() : ', file.readlines())


# Calling the readline() method for file objects, to read the next 4 bytes in a file
print('readlines(4) : ', file.readlines(4))

# Calling the readline() method for file objects, to read the next single line
print('readlines() : ', file.readlines())


# Calling the close() method for file objects, to close the file after we have read it.
file.close()

Output


readlines() : ['Hello there!\n', 'How are you doing? \n', 'May you have a blessed day!']
readlines(4) : []
readlines() : []


Program Analysis


As you may see in the output of the code, the program looks for a file named File.txt in the directory where this Python program is stored and if the file is found, it reads in the following sequence -

Note: We can even use the r+(read plus update mode), which allows us to not just read a file but also modify its content. For more on it, you will have to read our article, how to modify a file in Python.



Please share this article -





< Prev
Next >
< Python - File and File modes
Python - Write a File >



Advertisement

Please Subscribe

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




Advertisement



Notifications



Please check our latest addition

C#, PYTHON and DJANGO


Advertisement