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

Samad3 3

Uploaded by

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

Samad3 3

Uploaded by

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

DEPARTMENT OF

COMPUTER SCIENCE & ENGINEERING

Experiment 3.3

Student Name: Abdul Samad Khan UID: 21BCS1843


Branch: CSE Section/Group: 604 “A”
Semester: 4th Date: 09/05/2023
Subject Name: Programming in Python Lab Subject Code: 21CSP-259

1) Aim:
Program to demonstrate read and write data to the file in various modes.

2.) Code and output:

1) Write a Python program to generate 26 text files named A.txt, B.txt, and so
on up to Z.txt

Code import string, os if not os.path.exists("letters"):


os.makedirs("letters")
for letter in string.ascii_uppercase:
with open(letter + ".txt", "w") as f:
f.writelines(letter)
Output

Abdul Samad Khan 21BCS1843


DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

2) Write a Python program to create a file where all letters of English alphabet
are listed by specified number of letters on each line

Code

import string def


letters_file_line(n):
with open("words1.txt", "w") as f: alphabet = string.ascii_uppercase
letters = [alphabet[i:i + n] + "\n" for i in range(0, len(alphabet), n)]
f.writelines(letters)
letters_file_line(3)

Output

3) Write a Python program to read a random line from a file.

Code import
random def
random_line(fname):
lines = open(fname).read().splitlines()
return random.choice(lines)
print(random_line('testfile1.txt'))

Abdul Samad Khan 21BCS1843


DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

Output

4) Write a Python program to count the frequency of words in a file

Code

from collections import Counter def


word_count(fname):
with open(fname) as f:
return Counter(f.read().split())

print("Number of words in the file :",word_count("testfile1.txt"))

Output

5) Write a Python program to copy the contents of a file to another file


CODE:

from shutil import copyfile


copyfile('words1.txt', 'testfile1.txt')

Abdul Samad Khan 21BCS1843


DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

Output

Previous:

Updated:

Abdul Samad Khan 21BCS1843

You might also like