0% found this document useful (0 votes)
7 views4 pages

File Pgms

The document contains code snippets for performing various file operations like counting word occurrences in a file, counting characters in a file, searching for a word in a file, and merging contents of two files into a new file.

Uploaded by

maamamun4082
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views4 pages

File Pgms

The document contains code snippets for performing various file operations like counting word occurrences in a file, counting characters in a file, searching for a word in a file, and merging contents of two files into a new file.

Uploaded by

maamamun4082
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

1.

Occurences

fname = input("Enter file name: ")

word=input("Enter word to be searched:")

k=0

with open(fname, 'r') as f:

for line in f:

words = line.split()

for i in words:

if(i==word):

k=k+1

print("Occurrences of the word:")

print(k)

2.Vowels

def read_and_count():

lower_case=0

upper_case=0

alphabet=0

space=0

digit=0

string_count=0

with open("file3.txt") as iv:

c=iv.readlines()
for j in c:

for i in range(len(j)):

if(j[i].isalpha()):

alphabet+=1

if(j[i].isdigit()):

digit+=1

if(j[i].islower()):

lower_case+=1

if(j[i].isupper()):

upper_case+=1

if(j[i] == " "):

space+=1

string_count+=j.lower().count("hai")

print("Alphabets : ",alphabet)

print("Space : ",space)

print("Digits : ",digit)

print("Lower Case : ",lower_case)

print("Upper Case : ",upper_case)

print("Count of 'hai' : ",string_count)

read_and_count()

3.SEARCH

with open('file1.txt') as file:

contents = file.read()
search_word = input("enter a word you want to search in file: ")

if search_word in contents:

print ('word found')

else:

print ('word not found')

4.Merging

data = data2 = "";

# Reading data from file1

with open('file1.txt') as fp:

data = fp.read()

# Reading data from file2

with open('file2.txt') as fp:

data2 = fp.read()

# Merging 2 files

# To add the data of file2

# from next line

data += "\n"

data += data2

with open ('file3.txt', 'w') as fp:


fp.write(data)

You might also like