file handling notes (Python dilip sir)
file handling notes (Python dilip sir)
(9431180168)
1. #Program to write product names in a text file >>> %Run prodtxtfile_write.py
using write() method. Enter name of product: soap
Enter name of product: pasta
f = open("c:\DilipSir\product.txt","w") Enter name of product: rice
if not f: Enter name of product: wheatEnter
print("File does not exist ") name of product: sugar
else: product.txt file view
for i in range(5):
n = input("Enter name of product: ")
f.write(n+"\n") #to store product name
in file in different lines
f.close()
>>> %Run
poemtxtfile_countlines.py
4. #Write a function to count the number of lines
'W' = 4
with an alphabet "W". Consider the file "poem.txt"
contains the following lines.
def line_count():
f = open("c:\DilipSir\poem.txt", "r")
count = 0
for line in f:
if line[0] not in 'W':
count = count+1
f.close()
print("No. of lines not starting with 'W' = ",count)
>>> %Run
line_count()
poemtxtfile_countwords.py
5. #Write a function in python to count and display
>>> %Run
count_words()
poem_displaywords.py
6. #Write a function display_words() to read lines
Is - By is is is up By of of of is by
from a text file “poem.txt”, and display those
of my my
words which are less than 3 characters.
def display_words():
f = open("c:\DilipSir\poem.txt","r")
data = f.read() #reads the whole file
words = data.split() #list of words is formed
for w in words:
if len(w) < 3:
print(w,end = " ")
f.close()
PYTHON FILE HANDLING Dilip Sir
(9431180168)
>>> %Run
display_words()
poemtxtfile_count1words.py
7. #Write a function to count the words “Where” and
Total words are: 16
“the” present in a text file “poem.txt”.[Note that
the words “Where” and “the” are complete words]
def count_words():
f = open("c:\DilipSir\poem.txt","r")
count = 0
data = f.read()
words = data.split()
for w in words:
if w == "Where" or w == "the":
count = count +1
print("Total words are: ",count)
f.close()
count_words()
8. #Consider the following lines for the file Output
“sample.txt” and predict the output of the python
f = open("c:\DilipSir\sample.txt","r")
L = f.readline()
L2 = f.readline(18)
ch3 = f.read(10)
print(L2)
print(ch3)
print(f.readline())
f.close()
f = open("mytext.txt","r")
f.seek(8)
print(f.tell())
print(f.readline())
f.close()