Week- 7
- Write a Python code to merge two given file contents into a third file.
Answer:
We must permanently maintain our data as an essential component of programming in order to use it in the future. We should look for files that fulfill this criterion.
The most popular permanent storage method for our data is files.
Types of Files:
Files are of 2 types in python:
Text Files:
Usually we can use text files to store character data eg: abc.txt
Binary Files:
Usually we can use binary files to store binary data like images,video files, audio files etc...
Data1 = Data2 = ""
# Read data from file1
with open('file1.txt') as fp:
data1 = 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
Data1 += "\n"
Data1 += Data2
with open ('file3.txt', 'w') as fp:
fp.write(Data1)
seek():
We can use seek() method to move cursor(file pointer) to specified location. [Can you please seek the cursor to a particular location]
data="All Students are STUPIDS"
f=open("abc.txt","w")
f.write(data)
with open("abc.txt","r+") as f:
text=f.read()
print(text)
print("The Current Cursor Position: ",f.tell())
f.seek(17)
print("The Current Cursor Position: ",f.tell())
f.write("GEMS!!!")
f.seek(0)
text=f.read()
print("Data After Modification:")
print(text)
Output:
All Students are STUPIDS
The Current Cursor Position: 24
The Current Cursor Position: 17
Data After Modification:
All Students are GEMS!!!
- Write a Python code to open a given file and construct a function to check for given words present in it and display on found
import os,sys
fname=input("Enter File Name: ")
if os.path.isfile(fname):
print("File exists:",fname)
f=open(fname,"r")
else:
print("File does not exist:",fname)
sys.exit(0)
lcount=wcount=ccount=0
for line in f:
lcount=lcount+1
ccount=ccount+len(line)
words=line.split()
wcount=wcount+len(words)
print("The number of Lines:",lcount)
print("The number of Words:",wcount)
print("The number of Characters:",ccount)
for word in line.split():
print(word)
Output:
Enter File Name: file1.txt
File exists: abc.txt
The number of Lines: 1
The number of Words: 4
The number of Characters: 24
All
Students
are
GEMS!!!
- Write a Python code to Read text from a text file, find the word with most number of occurrences
Answer:
Method:1
def word_count(str):
counts = dict()
words = str.split()
for word in words:
if word in counts:
counts[word] += 1
else:
counts[word] = 1
return counts
print( word_count("the students of mrit are gems python and the students are working hard in python lab."))
Method:2
def word_count(str):
# Create an empty dictionary
counts = dict()
words = str.split()
# Loop through each line of the file
for word in words:
if word in counts:
counts[word] += 1
else:
counts[word] = 1
return counts
# Open the file in read mode
file = open("file2.txt", "r")
#read content of file to string
data = file.read()
# Print the number of occurrences of word
print( word_count(data))
Output:
{'welcome': 1, 'to': 1, 'v2smartclasses.com': 1, 'here': 1, 'you': 2, 'can': 1, 'learn': 1, 'programming': 1, 'languages.': 1, 'thank': 1, '!visit': 1, 'again!': 1}
- Write a function that reads a file file1 and displays the number of words, number of vowels, blank spaces, lower case letters and uppercase letters.
Answer:
def counting(filename):
# Opening the file in read mode
txt_file = open(filename, "r")
# Initialize three variables to count number of vowels,
# lines and characters respectively
vowel = 0
line = 0
character = 0
# Make a vowels list so that we can
# check whether the character is vowel or not
vowels_list = ['a', 'e', 'i', 'o', 'u',
'A', 'E', 'I', 'O', 'U']
# Iterate over the characters present in file
for alpha in txt_file.read():
# Checking if the current character is vowel or not
if alpha in vowels_list:
vowel += 1
# Checking if the current character is
# not vowel or new line character
elif alpha not in vowels_list and alpha != "\n":
character += 1
# Checking if the current character
# is new line character or not
elif alpha == "\n":
line += 1
# Print the desired output on the console.
print("Number of vowels in ", filename, " = ", vowel)
print("New Lines in ", filename, " = ", line)
print("Number of characters in ", filename, " = ", character)
# Calling the function counting which gives the desired output
counting('Myfile.txt')
Output:
Number of vowels in Myfile.txt = 25
New Lines in Myfile.txt = 3
Number of characters in Myfile.txt = 65