In: Computer Science
The code in this question shows three ways that one can read data from a file in a Python program.
Answer the following questions:
with open("rainfall.txt","r") as inFile:
aLine = inFile.readLine()
with open("rainfall.txt", "r") as inFile:
lineList = inFile.readLines()
with open("rainfall.txt", "r") as inFile:
fileString = inFile.read())
print(aLine)
print(lineList)
print(fileString)
Note - Since i dont have access to rainfall.txt file. I will explain you the roles of readLine(), readLines(), and read() functions though my text file-test.txt
Consider below text file -
(1) Now if use read() function here -
filepath='C:\\Users\\Preeti\\Desktop\\test.txt'
with open(filepath,"r") as inFile:
fileString = inFile.read()
print(fileString)
Output :
I am LINE 1 I am LINE 2 I am LINE 3 END OF LINES
Explanation - read() function basically reads the entire file and returns it if no size is mentioned.It accepts size as parameter i.e. read(size) . if size is mentioned then it returns quantity of data equal to size.Look at below example where i have given size as 15 -
filepath='C:\\Users\\Preeti\\Desktop\\test.txt'
with open(filepath,"r") as inFile:
fileString = inFile.read(15)
print(fileString)
Output :
I am LINE 1 I a
(2) if we use readline() function -
filepath='C:\\Users\\Preeti\\Desktop\\test.txt'
with open(filepath,"r") as inFile:
aLine = inFile.readline()
print(aLine)
Output :
I am LINE 1
Explanation - readline() function reads single line from the file. So only line 1 is is read and displayed. if you wish to read next line using readline() function , then use readline() function again as shown below
filepath='C:\\Users\\Preeti\\Desktop\\test.txt'
with open(filepath,"r") as inFile:
aLine = inFile.readline()
bLine = inFile.readline()
print(aLine)
print(bLine)
Output :
I am LINE 1 I am LINE 2
(3) if we use readlines() function -
filepath='C:\\Users\\Preeti\\Desktop\\test.txt'
with open(filepath,"r") as inFile:
lineList = inFile.readlines()
print(lineList)
Output :
['I am LINE 1\n', 'I am LINE 2\n', 'I am LINE 3\n', 'END OF LINES']
Explanation - readlines() function returns all the lines in a file in the list format where each element in the list is line from the file.