Text Files WS
Text Files WS
It consists of series of
lines of a set of letters, It consists of data with a
numbers or symbols specific pattern without any It consists of plain text with a
2 (String) delimiter. list of data with a delimiter.
It terminates a line
automatically when the
There is no specific EOL delimiter is not used after
4 Every line ends with EOL. character. data.
f = open("friends.txt")
l = f.readline()
l2 = f.readline(18)
ch3=f.read(10)
print(l2)
print(ch3)
print(f.readline())
f.close()
Output:
Friends are honest
, Friends
are best !
Explanation:
In line no. 2, f.readline() function reads first line and stores the output string in l
but not printed in the code, then it moves the pointer to next line in the file. In next
statement we have f.readline(18) which reads next 18 characters and place the
cursor at the next position i.e. comma (,) , in next statement f.read(10) reads next
10 characters and stores in ch3 variable and then cursor moves to the next position
and at last f.readline() function print() the entire line.
3. Write a function count_lines() to count and display the total number of
lines from the file. Consider above file – friends.txt.
def count_lines():
f = open("friends.txt")
cnt =0
for lines in f:
cnt+=1
print("no. of lines:",cnt)
f.close()
4. Write a function display_oddLines() to display odd number lines from the
text file. Consider above file – friends.txt.
def display_oddLines():
f = open("friends.txt")
cnt =0
for lines in f:
cnt+=1
if cnt%2!=0:
print(lines)
f.close()
5. Write a function cust_data() to ask user to enter their names and age to
store data in customer.txt file.
def cust_data():
name = input("Enter customer name:")
age=int(input("Enter customer age:"))
data = str([name,age])
f = open("customer.txt","w")
f.write(data)
f.close()
+