0% found this document useful (0 votes)
21 views

Python Exp 3.3

Uploaded by

PUNEET SHARMA
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)
21 views

Python Exp 3.3

Uploaded by

PUNEET SHARMA
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/ 13

EXPERIMENT–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):

with open("letter.txt", "w") as

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):

Sr. No. Parameters MarksObtained MaximumMarks


1.
2.
3.

You might also like