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

Unit 4 Python Ques -Ans

Uploaded by

urvashiishhrii
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Unit 4 Python Ques -Ans

Uploaded by

urvashiishhrii
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

1. Write a Python program to read an entire text file.

Sample Solution:-

def file_read(fname):

txt = open(fname)

print(txt.read())

file_read('test.txt')

2. Write a Python program to append text to a file and display the text..

Sample Solution:-

def file_read(fname):

from itertools import islice

with open(fname, "w") as myfile:

myfile.write("Python Exercises\n")

myfile.write("Java Exercises")

txt = open(fname)

print(txt.read())

file_read('abc.txt')

Sample Output:

Python Exercises
Java Exercises

5. Write a Python program to read a file line by line and store it into a list.
Python Code:

def file_read(fname):
with open(fname) as f:

#Content_list is the list that contains the read


lines.

content_list = f.readlines()

print(content_list)

file_read(\'test.txt\')

Flowchart:

6. Write a Python program to read a file line by line store it into a variable.

Sample Solution:-

Python Code:

def file_read(fname):

with open (fname, "r") as myfile:

data=myfile.readlines()
print(data)

file_read('test.txt')

7. Write a Python program to read a file line by line store it into an array.

Sample Solution:-

Python Code:

def file_read(fname):

content_array = []

with open(fname) as f:

#Content_list is the list that contains the read lines.

for line in f:

content_array.append(line)

print(content_array)

file_read('test.txt')

Sample Output:

['Welcome to w3resource.com.\n', 'Append this text.Append this


text.Append this text.\n', 'Append this text.\n
', 'Append this text.\n', 'Append this text.\n', 'Append this
text.\n']

8. Write a python program to find the longest words.


Python Code
def longest_word(filename):

with open(filename, 'r') as infile:


words = infile.read().split()

max_len = len(max(words, key=len))

return [word for word in words if len(word) == max_len]

print(longest_word('test.txt'))

Flowchart:

9. Write a Python program to count the number of lines in a text file.


to count the number of lines in a text file.

Sample Solution:-

Python Code:

def file_lengthy(fname):

with open(fname) as f:
for i, l in enumerate(f):

pass

return i + 1

print("Number of lines in the file:


",file_lengthy("test.txt"))

Sample Output:

Number of lines in the file: 6


Flowchart:

10. Write a Python program to count the frequency of words in a file.


unt the frequency of words in a file.

Sample Solution:-

Python 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("test.txt"))

Flowchart:

11. Write a Python program to get the file size of a plain file.

Sample Solution:-

Python Code:

def file_size(fname):

import os

statinfo = os.stat(fname)

return statinfo.st_size

print("File size in bytes of a plain file:


",file_size("test.txt"))
Copy
Sample Output:

File size in bytes of a plain file: 151


Flowchart:

12. Write a Python program to write a list to a file.

Sample Solution:-

Python Code:

color = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']

with open('abc.txt', "w") as myfile:

for c in color:

myfile.write("%s\n" % c)

content = open('abc.txt')

print(content.read())

Sample Output:

Red
Green
White
Black
Pink
Yellow
Flowchart:

13. Write a Python program to copy the contents of a file to another file .

Sample Solution:-

Python Code:

from shutil import copyfile

copyfile('test.py', 'abc.py')
Sample Output:

abc.py
Flowchart:

14. Write a Python program to combine each line from first file with the
corresponding line in second file.

Sample Solution:-

Python Code:

with open('abc.txt') as fh1, open('test.txt') as fh2:

for line1, line2 in zip(fh1, fh2):

# line1 from abc.txt, line2 from test.txt

print(line1+line2)

Sample Output:

Red
Welcome to w3resource.com.

Green
Append this text.Append this text.Append this text.
------
Yellow
Append this text.
Flowchart:

15. Write a Python program to read a random line from a file.

Sample Solution:-

Python Code:

import random

def random_line(fname):

lines = open(fname).read().splitlines()

return random.choice(lines)

print(random_line('test.txt'))
Copy
Sample Output:

Append this text.


Flowchart:

16. Write a Python program to assess if a file is closed or not.

Sample Solution:-

Python Code:

f = open('abc.txt','r')

print(f.closed)

f.close()

print(f.closed)

Sample Output:

False
True
Flowchart:
17. Write a Python program to remove newline characters from a file.

Sample Solution:

Python Code:

def remove_newlines(fname):

flist = open(fname).readlines()

return [s.rstrip('\n') for s in flist]

print(remove_newlines("test.txt"))

Sample Output:

['Welcome to w3resource.com.', 'Append this text.Append this


text.Append this text.', 'Append this text.', 'Ap
pend this text.', 'Append this text.', 'Append this text.']
Flowchart:
18. Write a Python program that takes a text file as input and returns the number
of words of a given text file.

Sample Solution:

Python Code:

def count_words(filepath):

with open(filepath) as f:

data = f.read()

data.replace(",", " ")

return len(data.split(" "))

print(count_words("words.txt"))

Sample Output:

33
Flowchart:
19. Write a Python program to extract characters from various text files and puts
them into a list.

Sample Solution:

Python Code

import glob

char_list = []

files_list = glob.glob("*.txt")

for file_elem in files_list:

with open(file_elem, "r") as f:

char_list.append(f.read())

print(char_list)

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

Sample Solution:

Python 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)
21. Write a Python program to create a file where all letters of English alphabet
are listed by specified number of letters on each line.

Sample Solution:

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

Copy
Output:

words1.txt
ABC
DEF
GHI
JKL
MNO
PQR
STU
VWX
YZ
Flowchart:

You might also like