Python - read() / readline() / readlines()

Python - read() / readline() / readlines()

readlines()  function 
  • readlines() returns a list. This list contains each line of the file as the list item 
  • readlines() reads the entire file at a time.
  • The default parameter value of readlines() function is  -1. This meant all the lines in the file shall be returned.
The difference between readline() and readlines() is that readline() read s each line at a time where as the readlines() reads the entire file and returns line by line. The read() returns the file as is as and is not returned as a list as like readline() and readlines().

The declaration for readline() is as follows:

file = open("log.txt", "r")
print(file.readline())
print(file.readline(10))

What happens if the parameter to the readline() has input more than exiting lines of the file?

If the log.txt has 10 lines and we try to print print(file.readline(25)), then only the existing 10 lines shall be returned.

If the file is present in any other location, other the python source file location, then the full path should be mentioned. Example: file = open("D:\Python-program\log.txt", "r")

The other file functions in Python are seek(), seekable(), close(), detach(), fileno(), flush(), isatty(), read(), readable(), tell(), truncate(), writeable(), write(), writelines()

Post a Comment

0 Comments