Computer Science
Consider the file "contacts.csv" created in above Q. and figure out what the following code is trying to do?
name = input("Enter name :")
file = open("contacts.csv", "r")
for line in file:
if name in line:
print(line)
Python File Handling
3 Likes
Answer
The code asks the user to enter a name. It then searches for the name in "contacts.csv" file. If found, the name and phone number are printed as the output.
Explanation
name = input("Enter name :")
— This line prompts the user to enter a name through the console, and the entered name is stored in the variablename
.file = open("contacts.csv", "r")
— This line opens the filecontacts.csv
in read mode and assigns the file object to the variablefile
.for line in file:
— This line initiates a for loop that iterates over each line in the file handle (file
represents the opened file object), which enables interaction with the file's content. During each iteration, the current line is stored in the variableline
.if name in line:
— Within the loop, it checks if the inputted name exists in the current line using thein
operator.print(line)
— If the name is found in the current line, this line prints the entire line to the console.
Answered By
2 Likes
Related Questions
Consider the file "poemBTH.txt" and predict the outputs of following code fragments if the file has been opened in filepointer file1 with the following code :
file1 = open("E:\\mydata\\poemBTH.txt", "r+")
(a)
print("A. Output 1") print(file1.read()) print()
(b)
print("B. Output 2") print(file1.readline()) print()
(c)
print("C. Output 3") print(file1.read(9)) print()
(d)
print("D. Output 4") print(file1.readline(9))
(e)
print("E. Output of Readlines function is") print(file1.readlines()) print()
NOTE. Consider the code fragments in succession, i.e., code (b) follows code (a), which means changes by code (a) remain intact when code (b) is executing. Similarly, code (c) follows (a) and (b), and so on.
What is the following code doing ?
file = open("contacts.csv", "a") name = input("Please enter name.") phno = input("Please enter phone number.") file.write(name + "," + phno + "\n")
Consider the file poemBTH.txt and predict the output of following code fragment. What exactly is the following code fragment doing ?
f = open("poemBTH.txt", "r") nl = 0 for line in f: nl += 1 print(nl)
Write a method in Python to read the content from a text file diary.txt line by line and display the same on screen.