Python Exp 3.3
Python Exp 3.3
3
Student Name: Gautam Prasad UID: 20BCS9611
Branch: CSE Section/Group: 810/B
Semester: 4th
AIM-OnthebasisofFile Handlingwriteandgivetheoutputofthefollowingsprograms
1. WriteaPythonprogramtogenerate26text filesnamedA.txt,B.txt,andsoonuptoZ.txt
2. WriteaPythonprogramtocreateafilewherealllettersofEnglishalphabetarelistedbyspecified
number oflettersoneach line
3. WriteaPythonprogramtoreadarandomlinefromafile.
4. WriteaPythonprogramtocountthefrequencyofwords inafile
5. WriteaPythonprogramtocopythecontentsofafiletoanotherfile
Solution-
1. WriteaPythonprogramtogenerate26text filesnamedA.txt,B.txt,andsoonuptoZ.txt
ProgramCode –
importstring,os
ifnotos.path.exists("letters"):os.make
dirs("letters")
for letter in
string.ascii_uppercase:withopen(le
tter+".txt","w")asf:
f.writelines(letter)
Screenshot ofCode-
Output-
2. WriteaPythonprogramtocreateafilewherealllettersofEnglishalphabetarelistedbyspecifiednumberof
lettersoneachline
ProgramCode –
importstring
defletters_file_line(n):
f:alphabet=string.ascii_uppercas
letters=[alphabet[i:i+n]+"\n"for iinrange(0,len(alphabet),n)]f.writelines(letters)
letters_file_line(3)
Screenshot ofCode-
Output-
3. WriteaPythonprogramtoreadarandomlinefromafile.
ProgramCode –
importrandom
defrandom_line(fname):
lines=open(fname).read().splitlines()returnr
andom.choice(lines)
print(random_line('apple.txt'))
Screenshot ofCode-
Output-
apple.txtfile-
4. WriteaPythonprogramtocountthefrequencyofwords inafile
ProgramCode –
fromcollections import
Counterdefword_count(fname):
withopen(fname)asf:
returnCounter(f.read().split())
print("Numberofwordsinthefile:",word_count("apple.txt"))
Screenshot ofCode-
Output-
apple.txtfile-
5. WriteaPythonprogramtocopythecontentsofafiletoanotherfile
ProgramCode –
from shutilimport
copyfilecopyfile('apple.txt','orange.tx
t')Screenshot ofCode-
Output-
EvaluationGrid(TobecreatedaspertheSOPandAssessmentguidelinesbythefaculty):