Example HTML page

File handling in Python

In this section i am going to write few sample programs related to files in Python programming.

I have created a file named with “thefile.txt”. This file contains the following text.

1.Write a python script to read first ‘5’ lines in the file. The file should contain minimum 7 lines.

def file(fname, nlines):
        from itertools import islice
        with open(fname) as f:
                for line in islice(f, nlines):
                        print(line)
file('thefile.txt',5)

Output

Hi

everyone

This

is

Sudhakar

2. Write a python script to read the content from the file and count the number of words in it.

fname = input("Enter file name: ")
num_words = 0
with open(fname, 'r') as f:
    for line in f:
        words = line.split()
        num_words += len(words)
        print(line)
print("Number of words:",num_words)
print(num_words)

Output

Enter file name: thefile.txt
Hieveryone

This

is

Sudhakar

Welcome

to

VMS
Number of words: 8
8

3. To read a character from the user and check the number of occurrences of this character in a given file. For example if the input is ‘s’, check how many number of time ‘s’ is in the file.

fname = input("Enter file name: ")
l=input("Enter letter to be searched:")
k = 0
 
with open(fname, 'r') as f:
    for line in f:
        words = line.split()
        for i in words:
            for letter in i:
                if(letter==l):
                    k=k+1
print("Occurrences of the letter:")
print(k)

Output

Enter file name: thefile.txt
Enter letter to be searched:s
Occurrences of the letter:
4

4.Write a python script to read a file and capitalize the first letter in each word.

fname = input("Enter file name: ")
with open(fname, 'r') as f:
    for line in f:
        l=line.title()
        print(l)

Output

Enter file name: thefile.txt
HiEveryone

This

Is

Sudhakar

Welcome

To

Vms

5. Write a python script to read the contents in reverse order.

filename=input("enter file name:")
for line in reversed(list(open(filename))):
        print(line.rstrip())

Output

enter file name:thefile.txt

VMS

to

Welcome

Sudhakar

is

This

everyone

Hi

 

 

 

 

Example HTML page

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest