Unlike readlines(), the readline() function in Python, used to read first line from the file.
If there are multiple statements of readline() function available in same program. Then first readline() returns first line, second readline() returns second line and so on.
The syntax to use readline() function in Python is:
where fo refers to the file object or handler. The size parameter is optional. If the size parameter of readline() provided as 10, then only first 10 characters of the line gets returned or read. Otherwise if this parameter is empty, then the whole line gets returned.
Before creating the program that uses readline() function to read the line from a file. We need to create a file first. Therefore I'm going to create a file say file.txt with some lines say 3 lines. The file must be saved within the current directory. Here is the snapshot of the current directory, with the file file.txt:
Now it's time to create an example program of readline() function:
fo = open("file.txt", "r") myline = fo.readline() print(myline)
The snapshot given below shows the sample output produced by this Python program:
See, only first line returned by the function readline(), that was printed on the output using print() statement. Now let's use the size parameter of this function as shown in the program given below:
fo = open("file.txt", "r") myline = fo.readline(7) print(myline)
This time, the output will be:
See, only first 7 characters including space is returned by the function readline() with 7 as parameter value.
Now the question is, what if file does not exist ?
Therefore, let's modify the above program, that handles error raised when the file given does not available in the current directory. Also the modified program, receives the name of file from user at run-time of the program. And I've used multiple readline() functions in single program shown below:
print("Enter File's Name: ", end="") filename = input() try: file_object = open(filename, "r") print("\n----Content of File----") print(file_object.readline()) print(file_object.readline()) except FileNotFoundError: print("\nThe given file is not available.")
Here is its sample run with user input file.txt:
The double newline printed, one due to the newline available as the last character of the line returned by readline(), and other due to the default behavior of print(). To avoid double newline, replace the following statement from above program:
with the statement given below:
Note - The end= parameter is used to change the default behavior of print(). To learn in detail, refer to its separate tutorial.
© Copyright 2021. All Rights Reserved.