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

Practical - 7 File Handling: Submitted By: Harshit Bansal (18BCS3805)

The document contains 5 questions and their solutions about file handling in Python. It introduces functions to read a file and store it in a list, find the longest words in a file, combine corresponding lines from two files, and check if a file is open or closed. Sample programs and outputs are provided for each question.

Uploaded by

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

Practical - 7 File Handling: Submitted By: Harshit Bansal (18BCS3805)

The document contains 5 questions and their solutions about file handling in Python. It introduces functions to read a file and store it in a list, find the longest words in a file, combine corresponding lines from two files, and check if a file is open or closed. Sample programs and outputs are provided for each question.

Uploaded by

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

Practical – 7

File Handling
Submitted By: Harshit Bansal (18BCS3805)
Q1: Write a Python program to read a file line by line and store it
into a list.
Program
def file_read(fname):
with open(fname) as f:
content_list = f.readlines()
print(content_list)

file_read('test.txt')

Output

Q2: Write a python program to find the longest words.


Program
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'))

Output
Q3: Write a python program to find the longest words.
Program
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'))

Output

Q4: Write a Python program to combine each line from first file
with the corresponding line in second file.
Program
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.txtg
print(line1+line2)

Output
Q5: Write a Python program to assess if a file is closed or not.
Program
f = open('abc.txt','r')
print(f.closed)
f.close()
print(f.closed)

Output

You might also like